home *** CD-ROM | disk | FTP | other *** search
/ Internet Info 1994 March / Internet Info CD-ROM (Walnut Creek) (March 1994).iso / answers / comp / C-faq / faq < prev    next >
Text File  |  1994-04-01  |  145KB  |  3,784 lines

  1. Path: bloom-beacon.mit.edu!hookup!news.sprintlink.net!connected.com!beauty!rwing!eskimo!scs
  2. From: scs@eskimo.com (Steve Summit)
  3. Newsgroups: comp.lang.c,comp.answers,news.answers
  4. Subject: comp.lang.c Answers to Frequently Asked Questions (FAQ List)
  5. Message-ID: <1994Apr01.0300.scs.0001@eskimo.com>
  6. Date: 1 Apr 94 11:04:00 GMT
  7. Expires: Tue, 3 May 1994 00:00:00 GMT
  8. Sender: scs@eskimo.com (Steve Summit)
  9. Reply-To: scs@eskimo.com
  10. Followup-To: poster
  11. Organization: none, at the moment
  12. Lines: 3765
  13. Approved: news-answers-request@MIT.Edu
  14. Supersedes: <1994Mar02.0102.scs.0002@eskimo.com>
  15. X-Archive-Name: C-faq/faq
  16. X-Last-Modified: March 1, 1994
  17. Xref: bloom-beacon.mit.edu comp.lang.c:37506 comp.answers:4382 news.answers:17167
  18.  
  19. Archive-name: C-faq/faq
  20. Comp-lang-c-archive-name: C-FAQ-list
  21.  
  22. [Last modified March 1, 1994 by scs.]
  23.  
  24. Certain topics come up again and again on this newsgroup.  They are good
  25. questions, and the answers may not be immediately obvious, but each time
  26. they recur, much net bandwidth and reader time is wasted on repetitive
  27. responses, and on tedious corrections to the incorrect answers which are
  28. inevitably posted.
  29.  
  30. This article, which is posted monthly, attempts to answer these common
  31. questions definitively and succinctly, so that net discussion can move
  32. on to more constructive topics without continual regression to first
  33. principles.
  34.  
  35. No mere newsgroup article can substitute for thoughtful perusal of a
  36. full-length tutorial or language reference manual.  Anyone interested
  37. enough in C to be following this newsgroup should also be interested
  38. enough to read and study one or more such manuals, preferably several
  39. times.  Some C books and compiler manuals are unfortunately inadequate;
  40. a few even perpetuate some of the myths which this article attempts to
  41. refute.  Several noteworthy books on C are listed in this article's
  42. bibliography.  Many of the questions and answers are cross-referenced to
  43. these books, for further study by the interested and dedicated reader
  44. (but beware of ANSI vs. ISO C Standard section numbers; see question
  45. 5.1).
  46.  
  47. If you have a question about C which is not answered in this article,
  48. first try to answer it by checking a few of the referenced books, or by
  49. asking knowledgeable colleagues, before posing your question to the net
  50. at large.  There are many people on the net who are happy to answer
  51. questions, but the volume of repetitive answers posted to one question,
  52. as well as the growing number of questions as the net attracts more
  53. readers, can become oppressive.  If you have questions or comments
  54. prompted by this article, please reply by mail rather than following up
  55. -- this article is meant to decrease net traffic, not increase it.
  56.  
  57. Besides listing frequently-asked questions, this article also summarizes
  58. frequently-posted answers.  Even if you know all the answers, it's worth
  59. skimming through this list once in a while, so that when you see one of
  60. its questions unwittingly posted, you won't have to waste time
  61. answering.
  62.  
  63. This article is always being improved.  Your input is welcomed.  Send
  64. your comments to scs@eskimo.com .
  65.  
  66. The questions answered here are divided into several categories:
  67.  
  68.      1. Null Pointers
  69.      2. Arrays and Pointers
  70.      3. Memory Allocation
  71.      4. Expressions
  72.      5. ANSI C
  73.      6. C Preprocessor
  74.      7. Variable-Length Argument Lists
  75.      8. Boolean Expressions and Variables
  76.      9. Structs, Enums, and Unions
  77.     10. Declarations
  78.     11. Stdio
  79.     12. Library Subroutines
  80.     13. Lint
  81.     14. Style
  82.     15. Floating Point
  83.     16. System Dependencies
  84.     17. Miscellaneous (Fortran to C converters, YACC grammars, etc.)
  85.  
  86. Herewith, some frequently-asked questions and their answers:
  87.  
  88.  
  89. Section 1. Null Pointers
  90.  
  91. 1.1:    What is this infamous null pointer, anyway?
  92.  
  93. A:    The language definition states that for each pointer type, there
  94.     is a special value -- the "null pointer" -- which is
  95.     distinguishable from all other pointer values and which is not
  96.     the address of any object or function.  That is, the address-of
  97.     operator & will never yield a null pointer, nor will a
  98.     successful call to malloc.  (malloc returns a null pointer when
  99.     it fails, and this is a typical use of null pointers: as a
  100.     "special" pointer value with some other meaning, usually "not
  101.     allocated" or "not pointing anywhere yet.")
  102.  
  103.     A null pointer is conceptually different from an uninitialized
  104.     pointer.  A null pointer is known not to point to any object; an
  105.     uninitialized pointer might point anywhere.  See also questions
  106.     3.1, 3.13, and 17.1.
  107.  
  108.     As mentioned in the definition above, there is a null pointer
  109.     for each pointer type, and the internal values of null pointers
  110.     for different types may be different.  Although programmers need
  111.     not know the internal values, the compiler must always be
  112.     informed which type of null pointer is required, so it can make
  113.     the distinction if necessary (see below).
  114.  
  115.     References: K&R I Sec. 5.4 pp. 97-8; K&R II Sec. 5.4 p. 102; H&S
  116.     Sec. 5.3 p. 91; ANSI Sec. 3.2.2.3 p. 38.
  117.  
  118. 1.2:    How do I "get" a null pointer in my programs?
  119.  
  120. A:    According to the language definition, a constant 0 in a pointer
  121.     context is converted into a null pointer at compile time.  That
  122.     is, in an initialization, assignment, or comparison when one
  123.     side is a variable or expression of pointer type, the compiler
  124.     can tell that a constant 0 on the other side requests a null
  125.     pointer, and generate the correctly-typed null pointer value.
  126.     Therefore, the following fragments are perfectly legal:
  127.  
  128.         char *p = 0;
  129.         if(p != 0)
  130.  
  131.     However, an argument being passed to a function is not
  132.     necessarily recognizable as a pointer context, and the compiler
  133.     may not be able to tell that an unadorned 0 "means" a null
  134.     pointer.  For instance, the Unix system call "execl" takes a
  135.     variable-length, null-pointer-terminated list of character
  136.     pointer arguments.  To generate a null pointer in a function
  137.     call context, an explicit cast is typically required, to force
  138.     the 0 to be in a pointer context:
  139.  
  140.         execl("/bin/sh", "sh", "-c", "ls", (char *)0);
  141.  
  142.     If the (char *) cast were omitted, the compiler would not know
  143.     to pass a null pointer, and would pass an integer 0 instead.
  144.     (Note that many Unix manuals get this example wrong.)
  145.  
  146.     When function prototypes are in scope, argument passing becomes
  147.     an "assignment context," and most casts may safely be omitted,
  148.     since the prototype tells the compiler that a pointer is
  149.     required, and of which type, enabling it to correctly convert
  150.     unadorned 0's.  Function prototypes cannot provide the types for
  151.     variable arguments in variable-length argument lists, however,
  152.     so explicit casts are still required for those arguments.  It is
  153.     safest always to cast null pointer function arguments, to guard
  154.     against varargs functions or those without prototypes, to allow
  155.     interim use of non-ANSI compilers, and to demonstrate that you
  156.     know what you are doing.  (Incidentally, it's also a simpler
  157.     rule to remember.)
  158.  
  159.     Summary:
  160.  
  161.         Unadorned 0 okay:    Explicit cast required:
  162.  
  163.         initialization        function call,
  164.                     no prototype in scope
  165.         assignment
  166.                     variable argument in
  167.         comparison        varargs function call
  168.  
  169.         function call,
  170.         prototype in scope,
  171.         fixed argument
  172.  
  173.     References: K&R I Sec. A7.7 p. 190, Sec. A7.14 p. 192; K&R II
  174.     Sec. A7.10 p. 207, Sec. A7.17 p. 209; H&S Sec. 4.6.3 p. 72; ANSI
  175.     Sec. 3.2.2.3 .
  176.  
  177. 1.3:    What is NULL and how is it #defined?
  178.  
  179. A:    As a matter of style, many people prefer not to have unadorned
  180.     0's scattered throughout their programs.  For this reason, the
  181.     preprocessor macro NULL is #defined (by <stdio.h> or
  182.     <stddef.h>), with value 0 (or (void *)0, about which more
  183.     later).  A programmer who wishes to make explicit the
  184.     distinction between 0 the integer and 0 the null pointer can
  185.     then use NULL whenever a null pointer is required.  This is a
  186.     stylistic convention only; the preprocessor turns NULL back to 0
  187.     which is then recognized by the compiler (in pointer contexts)
  188.     as before.  In particular, a cast may still be necessary before
  189.     NULL (as before 0) in a function call argument.  (The table
  190.     under question 1.2 above applies for NULL as well as 0.)
  191.  
  192.     NULL should _only_ be used for pointers; see question 1.8.
  193.  
  194.     References: K&R I Sec. 5.4 pp. 97-8; K&R II Sec. 5.4 p. 102; H&S
  195.     Sec. 13.1 p. 283; ANSI Sec. 4.1.5 p. 99, Sec. 3.2.2.3 p. 38,
  196.     Rationale Sec. 4.1.5 p. 74.
  197.  
  198. 1.4:    How should NULL be #defined on a machine which uses a nonzero
  199.     bit pattern as the internal representation of a null pointer?
  200.  
  201. A:    Programmers should never need to know the internal
  202.     representation(s) of null pointers, because they are normally
  203.     taken care of by the compiler.  If a machine uses a nonzero bit
  204.     pattern for null pointers, it is the compiler's responsibility
  205.     to generate it when the programmer requests, by writing "0" or
  206.     "NULL," a null pointer.  Therefore, #defining NULL as 0 on a
  207.     machine for which internal null pointers are nonzero is as valid
  208.     as on any other, because the compiler must (and can) still
  209.     generate the machine's correct null pointers in response to
  210.     unadorned 0's seen in pointer contexts.
  211.  
  212. 1.5:    If NULL were defined as follows:
  213.  
  214.         #define NULL (char *)0
  215.  
  216.     wouldn't that make function calls which pass an uncast NULL
  217.     work?
  218.  
  219. A:    Not in general.  The problem is that there are machines which
  220.     use different internal representations for pointers to different
  221.     types of data.  The suggested #definition would make uncast NULL
  222.     arguments to functions expecting pointers to characters to work
  223.     correctly, but pointer arguments to other types would still be
  224.     problematical, and legal constructions such as
  225.  
  226.         FILE *fp = NULL;
  227.  
  228.     could fail.
  229.  
  230.     Nevertheless, ANSI C allows the alternate
  231.  
  232.         #define NULL ((void *)0)
  233.  
  234.     definition for NULL.  Besides helping incorrect programs to work
  235.     (but only on machines with homogeneous pointers, thus
  236.     questionably valid assistance) this definition may catch
  237.     programs which use NULL incorrectly (e.g. when the ASCII  NUL
  238.     character was really intended; see question 1.8).
  239.  
  240.     References: ANSI Rationale Sec. 4.1.5 p. 74.
  241.  
  242. 1.6:    I use the preprocessor macro
  243.  
  244.         #define Nullptr(type) (type *)0
  245.  
  246.     to help me build null pointers of the correct type.
  247.  
  248. A:    This trick, though popular in some circles, does not buy much.
  249.     It is not needed in assignments and comparisons; see question
  250.     1.2.  It does not even save keystrokes.  Its use suggests to the
  251.     reader that the author is shaky on the subject of null pointers,
  252.     and requires the reader to check the #definition of the macro,
  253.     its invocations, and _all_ other pointer usages much more
  254.     carefully.  See also question 8.1.
  255.  
  256. 1.7:    Is the abbreviated pointer comparison "if(p)" to test for non-
  257.     null pointers valid?  What if the internal representation for
  258.     null pointers is nonzero?
  259.  
  260. A:    When C requires the boolean value of an expression (in the if,
  261.     while, for, and do statements, and with the &&, ||, !, and ?:
  262.     operators), a false value is produced when the expression
  263.     compares equal to zero, and a true value otherwise.  That is,
  264.     whenever one writes
  265.  
  266.         if(expr)
  267.  
  268.     where "expr" is any expression at all, the compiler essentially
  269.     acts as if it had been written as
  270.  
  271.         if(expr != 0)
  272.  
  273.     Substituting the trivial pointer expression "p" for "expr," we
  274.     have
  275.  
  276.         if(p)    is equivalent to        if(p != 0)
  277.  
  278.     and this is a comparison context, so the compiler can tell that
  279.     the (implicit) 0 is a null pointer, and use the correct value.
  280.     There is no trickery involved here; compilers do work this way,
  281.     and generate identical code for both statements.  The internal
  282.     representation of a pointer does _not_ matter.
  283.  
  284.     The boolean negation operator, !, can be described as follows:
  285.  
  286.         !expr    is essentially equivalent to    expr?0:1
  287.  
  288.     It is left as an exercise for the reader to show that
  289.  
  290.         if(!p)    is equivalent to        if(p == 0)
  291.  
  292.     "Abbreviations" such as if(p), though perfectly legal, are
  293.     considered by some to be bad style.
  294.  
  295.     See also question 8.2.
  296.  
  297.     References: K&R II Sec. A7.4.7 p. 204; H&S Sec. 5.3 p. 91; ANSI
  298.     Secs. 3.3.3.3, 3.3.9, 3.3.13, 3.3.14, 3.3.15, 3.6.4.1, and
  299.     3.6.5 .
  300.  
  301. 1.8:    If "NULL" and "0" are equivalent, which should I use?
  302.  
  303. A:    Many programmers believe that "NULL" should be used in all
  304.     pointer contexts, as a reminder that the value is to be thought
  305.     of as a pointer.  Others feel that the confusion surrounding
  306.     "NULL" and "0" is only compounded by hiding "0" behind a
  307.     #definition, and prefer to use unadorned "0" instead.  There is
  308.     no one right answer.  C programmers must understand that "NULL"
  309.     and "0" are interchangeable and that an uncast "0" is perfectly
  310.     acceptable in initialization, assignment, and comparison
  311.     contexts.  Any usage of "NULL" (as opposed to "0") should be
  312.     considered a gentle reminder that a pointer is involved;
  313.     programmers should not depend on it (either for their own
  314.     understanding or the compiler's) for distinguishing pointer 0's
  315.     from integer 0's.
  316.  
  317.     NULL should _not_ be used when another kind of 0 is required,
  318.     even though it might work, because doing so sends the wrong
  319.     stylistic message.  (ANSI allows the #definition of NULL to be
  320.     (void *)0, which will not work in non-pointer contexts.)  In
  321.     particular, do not use NULL when the ASCII null character (NUL)
  322.     is desired.  Provide your own definition
  323.  
  324.         #define NUL '\0'
  325.  
  326.     if you must.
  327.  
  328.     References: K&R II Sec. 5.4 p. 102.
  329.  
  330. 1.9:    But wouldn't it be better to use NULL (rather than 0) in case
  331.     the value of NULL changes, perhaps on a machine with nonzero
  332.     null pointers?
  333.  
  334. A:    No.  Although symbolic constants are often used in place of
  335.     numbers because the numbers might change, this is _not_ the
  336.     reason that NULL is used in place of 0.  Once again, the
  337.     language guarantees that source-code 0's (in pointer contexts)
  338.     generate null pointers.  NULL is used only as a stylistic
  339.     convention.
  340.  
  341. 1.10:    I'm confused.  NULL is guaranteed to be 0, but the null pointer
  342.     is not?
  343.  
  344. A:    When the term "null" or "NULL" is casually used, one of several
  345.     things may be meant:
  346.  
  347.     1.    The conceptual null pointer, the abstract language
  348.         concept defined in question 1.1.  It is implemented
  349.         with...
  350.  
  351.     2.    The internal (or run-time) representation of a null
  352.         pointer, which may or may not be all-bits-0 and which
  353.         may be different for different pointer types.  The
  354.         actual values should be of concern only to compiler
  355.         writers.  Authors of C programs never see them, since
  356.         they use...
  357.  
  358.     3.    The source code syntax for null pointers, which is the
  359.         single character "0".  It is often hidden behind...
  360.  
  361.     4.    The NULL macro, which is #defined to be "0" or
  362.         "(void *)0".  Finally, as red herrings, we have...
  363.  
  364.     5.    The ASCII null character (NUL), which does have all bits
  365.         zero, but has no necessary relation to the null pointer
  366.         except in name; and...
  367.  
  368.     6.    The "null string," which is another name for an empty
  369.         string ("").  The term "null string" can be confusing in
  370.         C (and should perhaps be avoided), because it involves a
  371.         null ('\0') character, but not a null pointer, which
  372.         brings us full circle...
  373.  
  374.     This article always uses the phrase "null pointer" (in lower
  375.     case) for sense 1, the character "0" for sense 3, and the
  376.     capitalized word "NULL" for sense 4.
  377.  
  378. 1.11:    Why is there so much confusion surrounding null pointers?  Why
  379.     do these questions come up so often?
  380.  
  381. A:    C programmers traditionally like to know more than they need to
  382.     about the underlying machine implementation.  The fact that null
  383.     pointers are represented both in source code, and internally to
  384.     most machines, as zero invites unwarranted assumptions.  The use
  385.     of a preprocessor macro (NULL) suggests that the value might
  386.     change later, or on some weird machine.  The construct
  387.     "if(p == 0)" is easily misread as calling for conversion of p to
  388.     an integral type, rather than 0 to a pointer type, before the
  389.     comparison.  Finally, the distinction between the several uses
  390.     of the term "null" (listed above) is often overlooked.
  391.  
  392.     One good way to wade out of the confusion is to imagine that C
  393.     had a keyword (perhaps "nil", like Pascal) with which null
  394.     pointers were requested.  The compiler could either turn "nil"
  395.     into the correct type of null pointer, when it could determine
  396.     the type from the source code, or complain when it could not.
  397.     Now, in fact, in C the keyword for a null pointer is not "nil"
  398.     but "0", which works almost as well, except that an uncast "0"
  399.     in a non-pointer context generates an integer zero instead of an
  400.     error message, and if that uncast 0 was supposed to be a null
  401.     pointer, the code may not work.
  402.  
  403. 1.12:    I'm still confused.  I just can't understand all this null
  404.     pointer stuff.
  405.  
  406. A:    Follow these two simple rules:
  407.  
  408.     1.    When you want to refer to a null pointer in source code,
  409.         use "0" or "NULL".
  410.  
  411.     2.    If the usage of "0" or "NULL" is an argument in a
  412.         function call, cast it to the pointer type expected by
  413.         the function being called.
  414.  
  415.     The rest of the discussion has to do with other people's
  416.     misunderstandings, or with the internal representation of null
  417.     pointers (which you shouldn't need to know), or with ANSI C
  418.     refinements.  Understand questions 1.1, 1.2, and 1.3, and
  419.     consider 1.8 and 1.11, and you'll do fine.
  420.  
  421. 1.13:    Given all the confusion surrounding null pointers, wouldn't it
  422.     be easier simply to require them to be represented internally by
  423.     zeroes?
  424.  
  425. A:    If for no other reason, doing so would be ill-advised because it
  426.     would unnecessarily constrain implementations which would
  427.     otherwise naturally represent null pointers by special, nonzero
  428.     bit patterns, particularly when those values would trigger
  429.     automatic hardware traps for invalid accesses.
  430.  
  431.     Besides, what would this requirement really accomplish?  Proper
  432.     understanding of null pointers does not require knowledge of the
  433.     internal representation, whether zero or nonzero.  Assuming that
  434.     null pointers are internally zero does not make any code easier
  435.     to write (except for a certain ill-advised usage of calloc; see
  436.     question 3.13).  Known-zero internal pointers would not obviate
  437.     casts in function calls, because the _size_ of the pointer might
  438.     still be different from that of an int.  (If "nil" were used to
  439.     request null pointers rather than "0," as mentioned in question
  440.     1.11, the urge to assume an internal zero representation would
  441.     not even arise.)
  442.  
  443. 1.14:    Seriously, have any actual machines really used nonzero null
  444.     pointers, or different representations for pointers to different
  445.     types?
  446.  
  447. A:    The Prime 50 series used segment 07777, offset 0 for the null
  448.     pointer, at least for PL/I.  Later models used segment 0, offset
  449.     0 for null pointers in C, necessitating new instructions such as
  450.     TCNP (Test C Null Pointer), evidently as a sop to all the extant
  451.     poorly-written C code which made incorrect assumptions.  Older,
  452.     word-addressed Prime machines were also notorious for requiring
  453.     larger byte pointers (char *'s) than word pointers (int *'s).
  454.  
  455.     The Eclipse MV series from Data General has three
  456.     architecturally supported pointer formats (word, byte, and bit
  457.     pointers), two of which are used by C compilers: byte pointers
  458.     for char * and void *, and word pointers for everything else.
  459.  
  460.     Some Honeywell-Bull mainframes use the bit pattern 06000 for
  461.     (internal) null pointers.
  462.  
  463.     The CDC Cyber 180 Series has 48-bit pointers consisting of a
  464.     ring, segment, and offset.  Most users (in ring 11) have null
  465.     pointers of 0xB00000000000.
  466.  
  467.     The Symbolics Lisp Machine, a tagged architecture, does not even
  468.     have conventional numeric pointers; it uses the pair <NIL, 0>
  469.     (basically a nonexistent <object, offset> handle) as a C null
  470.     pointer.
  471.  
  472.     Depending on the "memory model" in use, 80*86 processors (PC's)
  473.     may use 16 bit data pointers and 32 bit function pointers, or
  474.     vice versa.
  475.  
  476.     The old HP 3000 series computers use a different addressing
  477.     scheme for byte addresses than for word addresses; void and char
  478.     pointers therefore have a different representation than an int
  479.     (structure, etc.) pointer to the same address would have.
  480.  
  481. 1.15:    What does a run-time "null pointer assignment" error mean?  How
  482.     do I track it down?
  483.  
  484. A:    This message, which occurs only under MS-DOS (see, therefore,
  485.     section 16) means that you've written, via a null pointer, to
  486.     location zero.
  487.  
  488.     A debugger will usually let you set a data breakpoint on
  489.     location 0.  Alternately, you could write a bit of code to copy
  490.     20 or so bytes from location 0 into another buffer, and
  491.     periodically check that it hasn't changed.
  492.  
  493.  
  494. Section 2. Arrays and Pointers
  495.  
  496. 2.1:    I had the definition char a[6] in one source file, and in
  497.     another I declared extern char *a.  Why didn't it work?
  498.  
  499. A:    The declaration extern char *a simply does not match the actual
  500.     definition.  The type "pointer-to-type-T" is not the same as
  501.     "array-of-type-T."  Use extern char a[].
  502.  
  503.     References: CT&P Sec. 3.3 pp. 33-4, Sec. 4.5 pp. 64-5.
  504.  
  505. 2.2:    But I heard that char a[] was identical to char *a.
  506.  
  507. A:    Not at all.  (What you heard has to do with formal parameters to
  508.     functions; see question 2.4.)  Arrays are not pointers.  The
  509.     array declaration "char a[6];" requests that space for six
  510.     characters be set aside, to be known by the name "a."  That is,
  511.     there is a location named "a" at which six characters can sit.
  512.     The pointer declaration "char *p;" on the other hand, requests a
  513.     place which holds a pointer.  The pointer is to be known by the
  514.     name "p," and can point to any char (or contiguous array of
  515.     chars) anywhere.
  516.  
  517.     As usual, a picture is worth a thousand words.  The statements
  518.  
  519.         char a[] = "hello";
  520.         char *p = "world";
  521.  
  522.     would result in data structures which could be represented like
  523.     this:
  524.  
  525.            +---+---+---+---+---+---+
  526.         a: | h | e | l | l | o |\0 |
  527.            +---+---+---+---+---+---+
  528.  
  529.            +-----+     +---+---+---+---+---+---+
  530.         p: |  *======> | w | o | r | l | d |\0 |
  531.            +-----+     +---+---+---+---+---+---+
  532.  
  533.     It is important to realize that a reference like x[3] generates
  534.     different code depending on whether x is an array or a pointer.
  535.     Given the declarations above, when the compiler sees the
  536.     expression a[3], it emits code to start at the location "a,"
  537.     move three past it, and fetch the character there.  When it sees
  538.     the expression p[3], it emits code to start at the location "p,"
  539.     fetch the pointer value there, add three to the pointer, and
  540.     finally fetch the character pointed to.  In the example above,
  541.     both a[3] and p[3] happen to be the character 'l', but the
  542.     compiler gets there differently.  (See also questions 17.19 and
  543.     17.20.)
  544.  
  545. 2.3:    So what is meant by the "equivalence of pointers and arrays" in
  546.     C?
  547.  
  548. A:    Much of the confusion surrounding pointers in C can be traced to
  549.     a misunderstanding of this statement.  Saying that arrays and
  550.     pointers are "equivalent" neither means that they are identical
  551.     nor even interchangeable.
  552.  
  553.     "Equivalence" refers to the following key definition:
  554.  
  555.         An lvalue [see question 2.5] of type array-of-T
  556.         which appears in an expression decays (with
  557.         three exceptions) into a pointer to its first
  558.         element; the type of the resultant pointer is
  559.         pointer-to-T.
  560.  
  561.     (The exceptions are when the array is the operand of a sizeof or
  562.     & operator, or is a literal string initializer for a character
  563.     array.)
  564.  
  565.     As a consequence of this definition, there is no apparent
  566.     difference in the behavior of the "array subscripting" operator
  567.     [] as it applies to arrays and pointers.  In an expression of
  568.     the form a[i], the array reference "a" decays into a pointer,
  569.     following the rule above, and is then subscripted just as would
  570.     be a pointer variable in the expression p[i] (although the
  571.     eventual memory accesses will be different, as explained in
  572.     question 2.2).  In either case, the expression x[i] (where x is
  573.     an array or a pointer) is, by definition, identical to
  574.     *((x)+(i)).
  575.  
  576.     References: K&R I Sec. 5.3 pp. 93-6; K&R II Sec. 5.3 p. 99; H&S
  577.     Sec. 5.4.1 p. 93; ANSI Sec. 3.2.2.1, Sec. 3.3.2.1, Sec. 3.3.6 .
  578.  
  579. 2.4:    Then why are array and pointer declarations interchangeable as
  580.     function formal parameters?
  581.  
  582. A:    Since arrays decay immediately into pointers, an array is never
  583.     actually passed to a function.  As a convenience, any parameter
  584.     declarations which "look like" arrays, e.g.
  585.  
  586.         f(a)
  587.         char a[];
  588.  
  589.     are treated by the compiler as if they were pointers, since that
  590.     is what the function will receive if an array is passed:
  591.  
  592.         f(a)
  593.         char *a;
  594.  
  595.     This conversion holds only within function formal parameter
  596.     declarations, nowhere else.  If this conversion bothers you,
  597.     avoid it; many people have concluded that the confusion it
  598.     causes outweighs the small advantage of having the declaration
  599.     "look like" the call and/or the uses within the function.
  600.  
  601.     References: K&R I Sec. 5.3 p. 95, Sec. A10.1 p. 205; K&R II
  602.     Sec. 5.3 p. 100, Sec. A8.6.3 p. 218, Sec. A10.1 p. 226; H&S
  603.     Sec. 5.4.3 p. 96; ANSI Sec. 3.5.4.3, Sec. 3.7.1, CT&P Sec. 3.3
  604.     pp. 33-4.
  605.  
  606. 2.5:    How can an array be an lvalue, if you can't assign to it?
  607.  
  608. A:    The ANSI C Standard defines a "modifiable lvalue," which an
  609.     array is not.
  610.  
  611.     References: ANSI Sec. 3.2.2.1 p. 37.
  612.  
  613. 2.6:    Why doesn't sizeof properly report the size of an array which is
  614.     a parameter to a function?
  615.  
  616. A:    The sizeof operator reports the size of the pointer parameter
  617.     which the function actually receives (see question 2.4).
  618.  
  619. 2.7:    Someone explained to me that arrays were really just constant
  620.     pointers.
  621.  
  622. A:    This is a bit of an oversimplification.  An array name is
  623.     "constant" in that it cannot be assigned to, but an array is
  624.     _not_ a pointer, as the discussion and pictures in question 2.2
  625.     should make clear.
  626.  
  627. 2.8:    Practically speaking, what is the difference between arrays and
  628.     pointers?
  629.  
  630. A:    Arrays automatically allocate space, but can't be relocated or
  631.     resized.  Pointers must be explicitly assigned to point to
  632.     allocated space (perhaps using malloc), but can be reassigned
  633.     (i.e. pointed at different objects) at will, and have many other
  634.     uses besides serving as the base of blocks of memory.
  635.  
  636.     Due to the so-called equivalence of arrays and pointers (see
  637.     question 2.3), arrays and pointers often seem interchangeable,
  638.     and in particular a pointer to a block of memory assigned by
  639.     malloc is frequently treated (and can be referenced using []
  640.     exactly) as if it were a true array.  (See question 2.14; see
  641.     also question 17.20.)
  642.  
  643. 2.9:    I came across some "joke" code containing the "expression"
  644.     5["abcdef"] .  How can this be legal C?
  645.  
  646. A:    Yes, Virginia, array subscripting is commutative in C.  This
  647.     curious fact follows from the pointer definition of array
  648.     subscripting, namely that a[e] is identical to *((a)+(e)), for
  649.     _any_ expression e and primary expression a, as long as one of
  650.     them is a pointer expression and one is integral.  This
  651.     unsuspected commutativity is often mentioned in C texts as if it
  652.     were something to be proud of, but it finds no useful
  653.     application outside of the Obfuscated C Contest (see question
  654.     17.13).
  655.  
  656.     References: ANSI Rationale Sec. 3.3.2.1 p. 41.
  657.  
  658. 2.10:    My compiler complained when I passed a two-dimensional array to
  659.     a routine expecting a pointer to a pointer.
  660.  
  661. A:    The rule by which arrays decay into pointers is not applied
  662.     recursively.  An array of arrays (i.e. a two-dimensional array
  663.     in C) decays into a pointer to an array, not a pointer to a
  664.     pointer.  Pointers to arrays can be confusing, and must be
  665.     treated carefully.  (The confusion is heightened by the
  666.     existence of incorrect compilers, including some versions of pcc
  667.     and pcc-derived lint's, which improperly accept assignments of
  668.     multi-dimensional arrays to multi-level pointers.)  If you are
  669.     passing a two-dimensional array to a function:
  670.  
  671.         int array[NROWS][NCOLUMNS];
  672.         f(array);
  673.  
  674.     the function's declaration should match:
  675.  
  676.         f(int a[][NCOLUMNS]) {...}
  677.     or
  678.         f(int (*ap)[NCOLUMNS]) {...}    /* ap is a pointer to an array */
  679.  
  680.     In the first declaration, the compiler performs the usual
  681.     implicit parameter rewriting of "array of array" to "pointer to
  682.     array;" in the second form the pointer declaration is explicit.
  683.     Since the called function does not allocate space for the array,
  684.     it does not need to know the overall size, so the number of
  685.     "rows," NROWS, can be omitted.  The "shape" of the array is
  686.     still important, so the "column" dimension NCOLUMNS (and, for 3-
  687.     or more dimensional arrays, the intervening ones) must be
  688.     included.
  689.  
  690.     If a function is already declared as accepting a pointer to a
  691.     pointer, it is probably incorrect to pass a two-dimensional
  692.     array directly to it.
  693.  
  694.     References: K&R I Sec. 5.10 p. 110; K&R II Sec. 5.9 p. 113.
  695.  
  696. 2.11:    How do I write functions which accept 2-dimensional arrays when
  697.     the "width" is not known at compile time?
  698.  
  699. A:    It's not easy.  One way is to pass in a pointer to the [0][0]
  700.     element, along with the two dimensions, and simulate array
  701.     subscripting "by hand:"
  702.  
  703.         f2(aryp, nrows, ncolumns)
  704.         int *aryp;
  705.         int nrows, ncolumns;
  706.         { ... ary[i][j] is really aryp[i * ncolumns + j] ... }
  707.  
  708.     This function could be called with the array from question 2.10
  709.     as
  710.  
  711.         f2(&array[0][0], NROWS, NCOLUMNS);
  712.  
  713.     It must be noted, however, that a program which performs
  714.     multidimensional array subscripting "by hand" in this way is not
  715.     in strict conformance with the ANSI C Standard; the behavior of
  716.     accessing (&array[0][0])[x] is not defined for x > NCOLUMNS.
  717.  
  718.     gcc allows local arrays to be declared having sizes which are
  719.     specified by a function's arguments, but this is a nonstandard
  720.     extension.
  721.  
  722.     See also question 2.15.
  723.  
  724. 2.12:    How do I declare a pointer to an array?
  725.  
  726. A:    Usually, you don't want to.  When people speak casually of a
  727.     pointer to an array, they usually mean a pointer to its first
  728.     element.
  729.  
  730.     Instead of a pointer to an array, consider using a pointer to
  731.     one of the array's elements.  Arrays of type T decay into
  732.     pointers to type T (see question 2.3), which is convenient;
  733.     subscripting or incrementing the resultant pointer accesses the
  734.     individual members of the array.  True pointers to arrays, when
  735.     subscripted or incremented, step over entire arrays, and are
  736.     generally only useful when operating on arrays of arrays, if at
  737.     all.  (See question 2.10 above.)
  738.  
  739.     If you really need to declare a pointer to an entire array, use
  740.     something like "int (*ap)[N];" where N is the size of the array.
  741.     (See also question 10.4.)  If the size of the array is unknown,
  742.     N can be omitted, but the resulting type, "pointer to array of
  743.     unknown size," is useless.
  744.  
  745. 2.13:    Since array references decay to pointers, given
  746.  
  747.         int array[NROWS][NCOLUMNS];
  748.  
  749.     what's the difference between array and &array?
  750.  
  751. A:    Under ANSI/ISO Standard C, &array yields a pointer, of type
  752.     pointer-to-array-of-T, to the entire array (see also question
  753.     2.12).  Under pre-ANSI C, the & in &array generally elicited a
  754.     warning, and was generally ignored.  Under all C compilers, an
  755.     unadorned reference to an array yields a pointer, of type
  756.     pointer-to-T, to the array's first element.  (See also question
  757.     2.3.)
  758.  
  759. 2.14:    How can I dynamically allocate a multidimensional array?
  760.  
  761. A:    It is usually best to allocate an array of pointers, and then
  762.     initialize each pointer to a dynamically-allocated "row."  Here
  763.     is a two-dimensional example:
  764.  
  765.         int **array1 = (int **)malloc(nrows * sizeof(int *));
  766.         for(i = 0; i < nrows; i++)
  767.             array1[i] = (int *)malloc(ncolumns * sizeof(int));
  768.  
  769.     (In "real" code, of course, malloc would be declared correctly,
  770.     and each return value checked.)
  771.  
  772.     You can keep the array's contents contiguous, while making later
  773.     reallocation of individual rows difficult, with a bit of
  774.     explicit pointer arithmetic:
  775.  
  776.         int **array2 = (int **)malloc(nrows * sizeof(int *));
  777.         array2[0] = (int *)malloc(nrows * ncolumns * sizeof(int));
  778.         for(i = 1; i < nrows; i++)
  779.             array2[i] = array2[0] + i * ncolumns;
  780.  
  781.     In either case, the elements of the dynamic array can be
  782.     accessed with normal-looking array subscripts: array[i][j].
  783.  
  784.     If the double indirection implied by the above schemes is for
  785.     some reason unacceptable, you can simulate a two-dimensional
  786.     array with a single, dynamically-allocated one-dimensional
  787.     array:
  788.  
  789.         int *array3 = (int *)malloc(nrows * ncolumns * sizeof(int));
  790.  
  791.     However, you must now perform subscript calculations manually,
  792.     accessing the i,jth element with array3[i * ncolumns + j].  (A
  793.     macro can hide the explicit calculation, but invoking it then
  794.     requires parentheses and commas which don't look exactly like
  795.     multidimensional array subscripts.)
  796.  
  797.     Finally, you can use pointers-to-arrays:
  798.  
  799.         int (*array4)[NCOLUMNS] =
  800.             (int (*)[NCOLUMNS])malloc(nrows * sizeof(*array4));
  801.  
  802.     , but the syntax gets horrific and all but one dimension must be
  803.     known at compile time.
  804.  
  805.     With all of these techniques, you may of course need to remember
  806.     to free the arrays (which may take several steps; see question
  807.     3.9) when they are no longer needed, and you cannot necessarily
  808.     intermix the dynamically-allocated arrays with conventional,
  809.     statically-allocated ones (see question 2.15 below, and also
  810.     question 2.10).
  811.  
  812. 2.15:    How can I use statically- and dynamically-allocated
  813.     multidimensional arrays interchangeably when passing them to
  814.     functions?
  815.  
  816. A:    There is no single perfect method.  Given a function f1()
  817.     similar to the f() of question 2.10, the array as declared in
  818.     question 2.10, f2() as declared in question 2.11, array1,
  819.     array2, array3, and array4 as declared in question 2.14, and a
  820.     function f3() declared as:
  821.  
  822.         f3(pp, m, n)
  823.         int **pp;
  824.         int m, n;
  825.  
  826.     ; the following calls should work as expected:
  827.  
  828.         f1(array, NROWS, NCOLUMNS);
  829.         f1(array4, nrows, NCOLUMNS);
  830.         f2(&array[0][0], NROWS, NCOLUMNS);
  831.         f2(*array2, nrows, ncolumns);
  832.         f2(array3, nrows, ncolumns);
  833.         f2(*array4, nrows, NCOLUMNS);
  834.         f3(array1, nrows, ncolumns);
  835.         f3(array2, nrows, ncolumns);
  836.  
  837.     The following two calls would probably work, but involve
  838.     questionable casts, and work only if the dynamic ncolumns
  839.     matches the static NCOLUMNS:
  840.  
  841.         f1((int (*)[NCOLUMNS])(*array2), nrows, ncolumns);
  842.         f1((int (*)[NCOLUMNS])array3, nrows, ncolumns);
  843.  
  844.     It must again be noted that passing &array[0][0] to f2() is not
  845.     strictly conforming; see question 2.11.
  846.  
  847.     If you can understand why all of the above calls work and are
  848.     written as they are, and if you understand why the combinations
  849.     that are not listed would not work, then you have a _very_ good
  850.     understanding of arrays and pointers (and several other areas)
  851.     in C.
  852.  
  853. 2.16:    Here's a neat trick: if I write
  854.  
  855.         int realarray[10];
  856.         int *array = &realarray[-1];
  857.  
  858.     I can treat "array" as if it were a 1-based array.
  859.  
  860. A:    Although this technique is attractive (and was used in old
  861.     editions of the book Numerical Recipes in C), it does not
  862.     conform to the C standards.  Pointer arithmetic is defined only
  863.     as long as the pointer points within the same allocated block of
  864.     memory, or to the imaginary "terminating" element one past it;
  865.     otherwise, the behavior is undefined, _even if the pointer is
  866.     not dereferenced_.  The code above could fail if, while
  867.     subtracting the offset, an illegal address were generated
  868.     (perhaps because the address tried to "wrap around" past the
  869.     beginning of some memory segment).
  870.  
  871.     References: ANSI Sec. 3.3.6 p. 48, Rationale Sec. 3.2.2.3 p. 38;
  872.     K&R II Sec. 5.3 p. 100, Sec. 5.4 pp. 102-3, Sec. A7.7 pp. 205-6.
  873.  
  874. 2.17:    I passed a pointer to a function which initialized it:
  875.  
  876.         ...
  877.         int *ip;
  878.         f(ip);
  879.         ...
  880.  
  881.         void f(ip)
  882.         int *ip;
  883.         {
  884.             static int dummy = 5;
  885.             ip = &dummy;
  886.         }
  887.  
  888.     , but the pointer in the caller was unchanged.
  889.  
  890. A:    Did the function try to initialize the pointer itself, or just
  891.     what it pointed to?  Remember that arguments in C are passed by
  892.     value.  The called function altered only the passed copy of the
  893.     pointer.  You'll want to pass the address of the pointer (the
  894.     function will end up accepting a pointer-to-a-pointer).
  895.  
  896. 2.18:    I have a char * pointer that happens to point to some ints, and
  897.     I want to step it over them.  Why doesn't
  898.  
  899.         ((int *)p)++;
  900.  
  901.     work?
  902.  
  903. A:    In C, a cast operator does not mean "pretend these bits have a
  904.     different type, and treat them accordingly;" it is a conversion
  905.     operator, and by definition it yields an rvalue, which cannot be
  906.     assigned to, or incremented with ++.  (It is an anomaly in pcc-
  907.     derived compilers, and an extension in gcc, that expressions
  908.     such as the above are ever accepted.)  Say what you mean: use
  909.  
  910.         p = (char *)((int *)p + 1);
  911.  
  912.     , or simply
  913.  
  914.         p += sizeof(int);
  915.  
  916.     References: ANSI Sec. 3.3.4, Rationale Sec. 3.3.2.4 p. 43.
  917.  
  918. 2.19:    Can I use a void ** pointer to pass a generic pointer to a
  919.     function by reference?
  920.  
  921. A:    Not portably.  There is no generic pointer-to-pointer type in C.
  922.     void * acts as a generic pointer only because conversions are
  923.     applied automatically when other pointer types are assigned to
  924.     and from void *'s; these conversions cannot be performed (the
  925.     correct underlying pointer type is not known) if an attempt is
  926.     made to indirect upon a void ** value which points at something
  927.     other than a void *.
  928.  
  929.  
  930. Section 3. Memory Allocation
  931.  
  932. 3.1:    Why doesn't this fragment work?
  933.  
  934.         char *answer;
  935.         printf("Type something:\n");
  936.         gets(answer);
  937.         printf("You typed \"%s\"\n", answer);
  938.  
  939. A:    The pointer variable "answer," which is handed to the gets
  940.     function as the location into which the response should be
  941.     stored, has not been set to point to any valid storage.  That
  942.     is, we cannot say where the pointer "answer" points.  (Since
  943.     local variables are not initialized, and typically contain
  944.     garbage, it is not even guaranteed that "answer" starts out as a
  945.     null pointer.  See question 17.1.)
  946.  
  947.     The simplest way to correct the question-asking program is to
  948.     use a local array, instead of a pointer, and let the compiler
  949.     worry about allocation:
  950.  
  951.         #include <string.h>
  952.  
  953.         char answer[100], *p;
  954.         printf("Type something:\n");
  955.         fgets(answer, sizeof(answer), stdin);
  956.         if((p = strchr(answer, '\n')) != NULL)
  957.             *p = '\0';
  958.         printf("You typed \"%s\"\n", answer);
  959.  
  960.     Note that this example also uses fgets instead of gets (always a
  961.     good idea; see question 11.5), allowing the size of the array to
  962.     be specified, so that the end of the array will not be
  963.     overwritten if the user types an overly-long line.
  964.     (Unfortunately for this example, fgets does not automatically
  965.     delete the trailing \n, as gets would.)  It would also be
  966.     possible to use malloc to allocate the answer buffer.
  967.  
  968. 3.2:    I can't get strcat to work.  I tried
  969.  
  970.         char *s1 = "Hello, ";
  971.         char *s2 = "world!";
  972.         char *s3 = strcat(s1, s2);
  973.  
  974.     but I got strange results.
  975.  
  976. A:    Again, the problem is that space for the concatenated result is
  977.     not properly allocated.  C does not provide an automatically-
  978.     managed string type.  C compilers only allocate memory for
  979.     objects explicitly mentioned in the source code (in the case of
  980.     "strings," this includes character arrays and string literals).
  981.     The programmer must arrange (explicitly) for sufficient space
  982.     for the results of run-time operations such as string
  983.     concatenation, typically by declaring arrays, or by calling
  984.     malloc.
  985.  
  986.     strcat performs no allocation; the second string is appended to
  987.     the first one, in place.  Therefore, one fix would be to declare
  988.     the first string as an array with sufficient space:
  989.  
  990.         char s1[20] = "Hello, ";
  991.  
  992.     Since strcat returns the value of its first argument (s1, in
  993.     this case), the s3 variable is superfluous.
  994.  
  995.     References: CT&P Sec. 3.2 p. 32.
  996.  
  997. 3.3:    But the man page for strcat says that it takes two char *'s as
  998.     arguments.  How am I supposed to know to allocate things?
  999.  
  1000. A:    In general, when using pointers you _always_ have to consider
  1001.     memory allocation, at least to make sure that the compiler is
  1002.     doing it for you.  If a library routine's documentation does not
  1003.     explicitly mention allocation, it is usually the caller's
  1004.     problem.
  1005.  
  1006.     The Synopsis section at the top of a Unix-style man page can be
  1007.     misleading.  The code fragments presented there are closer to
  1008.     the function definition used by the call's implementor than the
  1009.     invocation used by the caller.  In particular, many routines
  1010.     which accept pointers (e.g. to structs or strings), are usually
  1011.     called with the address of some object (a struct, or an array --
  1012.     see questions 2.3 and 2.4.)  Another common example is stat().
  1013.  
  1014. 3.4:    I have a function that is supposed to return a string, but when
  1015.     it returns to its caller, the returned string is garbage.
  1016.  
  1017. A:    Make sure that the memory to which the function returns a
  1018.     pointer is correctly allocated.  The returned pointer should be
  1019.     to a statically-allocated buffer, or to a buffer passed in by
  1020.     the caller, but _not_ to a local (auto) array.  In other words,
  1021.     never do something like
  1022.  
  1023.         char *f()
  1024.         {
  1025.             char buf[10];
  1026.             /* ... */
  1027.             return buf;
  1028.         }
  1029.  
  1030.     One fix would to to declare the buffer as
  1031.  
  1032.             static char buf[10];
  1033.  
  1034.     See also question 17.5.
  1035.  
  1036. 3.5:    Why does some code carefully cast the values returned by malloc
  1037.     to the pointer type being allocated?
  1038.  
  1039. A:    Before ANSI/ISO Standard C introduced the void * generic pointer
  1040.     type, these casts were typically required to silence warnings
  1041.     about assignment between incompatible pointer types.
  1042.  
  1043. 3.6:    You can't use dynamically-allocated memory after you free it,
  1044.     can you?
  1045.  
  1046. A:    No.  Some early documentation for malloc stated that the
  1047.     contents of freed memory was "left undisturbed;" this ill-
  1048.     advised guarantee was never universal and is not required by
  1049.     ANSI.
  1050.  
  1051.     Few programmers would use the contents of freed memory
  1052.     deliberately, but it is easy to do so accidentally.  Consider
  1053.     the following (correct) code for freeing a singly-linked list:
  1054.  
  1055.         struct list *listp, *nextp;
  1056.         for(listp = base; listp != NULL; listp = nextp) {
  1057.             nextp = listp->next;
  1058.             free((char *)listp);
  1059.         }
  1060.  
  1061.     and notice what would happen if the more-obvious loop iteration
  1062.     expression listp = listp->next were used, without the temporary
  1063.     nextp pointer.
  1064.  
  1065.     References: ANSI Rationale Sec. 4.10.3.2 p. 102; CT&P Sec. 7.10
  1066.     p. 95.
  1067.  
  1068. 3.7:    How does free() know how many bytes to free?
  1069.  
  1070. A:    The malloc/free package remembers the size of each block it
  1071.     allocates and returns, so it is not necessary to remind it of
  1072.     the size when freeing.
  1073.  
  1074. 3.8:    So can I query the malloc package to find out how big an
  1075.     allocated block is?
  1076.  
  1077. A:    Not portably.
  1078.  
  1079. 3.9:    I'm allocating structures which contain pointers to other
  1080.     dynamically-allocated objects.  When I free a structure, do I
  1081.     have to free each subsidiary pointer first?
  1082.  
  1083. A:    Yes.  In general, you must arrange that each pointer returned
  1084.     from malloc be individually passed to free, exactly once (if it
  1085.     is freed at all).
  1086.  
  1087. 3.10:    I have a program which mallocs but then frees a lot of memory,
  1088.     but memory usage (as reported by ps) doesn't seem to go back
  1089.     down.
  1090.  
  1091. A:    Most implementations of malloc/free do not return freed memory
  1092.     to the operating system (if there is one), but merely make it
  1093.     available for future malloc calls.
  1094.  
  1095. 3.11:    Must I free allocated memory before the program exits?
  1096.  
  1097. A:    You shouldn't have to.  A real operating system definitively
  1098.     reclaims all memory when a program exits.  Nevertheless, some
  1099.     personal computers are said not to reliably recover memory, and
  1100.     all that can be inferred from the ANSI/ISO C Standard is that it
  1101.     is a "quality of implementation issue."
  1102.  
  1103.     References: ANSI Sec. 4.10.3.2 .
  1104.  
  1105. 3.12:    Is it legal to pass a null pointer as the first argument to
  1106.     realloc()?  Why would you want to?
  1107.  
  1108. A:    ANSI C sanctions this usage (and the related realloc(..., 0),
  1109.     which frees), but several earlier implementations do not support
  1110.     it, so it is not widely portable.  Passing an initially-null
  1111.     pointer to realloc can make it easier to write a self-starting
  1112.     incremental allocation algorithm.
  1113.  
  1114.     References: ANSI Sec. 4.10.3.4 .
  1115.  
  1116. 3.13:    What is the difference between calloc and malloc?  Is it safe to
  1117.     use calloc's zero-fill guarantee for pointer and floating-point
  1118.     values?  Does free work on memory allocated with calloc, or do
  1119.     you need a cfree?
  1120.  
  1121. A:    calloc(m, n) is essentially equivalent to
  1122.  
  1123.         p = malloc(m * n);
  1124.         memset(p, 0, m * n);
  1125.  
  1126.     The zero fill is all-bits-zero, and does not therefore guarantee
  1127.     useful zero values for pointers (see section 1 of this list) or
  1128.     floating-point values.  free can (and should) be used to free
  1129.     the memory allocated by calloc.
  1130.  
  1131.     References: ANSI Secs. 4.10.3 to 4.10.3.2 .
  1132.  
  1133. 3.14:    What is alloca and why is its use discouraged?
  1134.  
  1135. A:    alloca allocates memory which is automatically freed when the
  1136.     function which called alloca returns.  That is, memory allocated
  1137.     with alloca is local to a particular function's "stack frame" or
  1138.     context.
  1139.  
  1140.     alloca cannot be written portably, and is difficult to implement
  1141.     on machines without a stack.  Its use is problematical (and the
  1142.     obvious implementation on a stack-based machine fails) when its
  1143.     return value is passed directly to another function, as in
  1144.     fgets(alloca(100), 100, stdin).
  1145.  
  1146.     For these reasons, alloca cannot be used in programs which must
  1147.     be widely portable, no matter how useful it might be.
  1148.  
  1149.     References: ANSI Rationale Sec. 4.10.3 p. 102.
  1150.  
  1151.  
  1152. Section 4. Expressions
  1153.  
  1154. 4.1:    Why doesn't this code:
  1155.  
  1156.         a[i] = i++;
  1157.  
  1158.     work?
  1159.  
  1160. A:    The subexpression i++ causes a side effect -- it modifies i's
  1161.     value -- which leads to undefined behavior if i is also
  1162.     referenced elsewhere in the same expression.  (Note that
  1163.     although the language in K&R suggests that the behavior of this
  1164.     expression is unspecified, the ANSI/ISO C Standard makes the
  1165.     stronger statement that it is undefined -- see question 5.23.)
  1166.  
  1167.     References: ANSI Sec. 3.3 p. 39.
  1168.  
  1169. 4.2:    Under my compiler, the code
  1170.  
  1171.         int i = 7;
  1172.         printf("%d\n", i++ * i++);
  1173.  
  1174.     prints 49.  Regardless of the order of evaluation, shouldn't it
  1175.     print 56?
  1176.  
  1177. A:    Although the postincrement and postdecrement operators ++ and --
  1178.     perform the operations after yielding the former value, the
  1179.     implication of "after" is often misunderstood.  It is _not_
  1180.     guaranteed that the operation is performed immediately after
  1181.     giving up the previous value and before any other part of the
  1182.     expression is evaluated.  It is merely guaranteed that the
  1183.     update will be performed sometime before the expression is
  1184.     considered "finished" (before the next "sequence point," in ANSI
  1185.     C's terminology).  In the example, the compiler chose to
  1186.     multiply the previous value by itself and to perform both
  1187.     increments afterwards.
  1188.  
  1189.     The behavior of code which contains multiple, ambiguous side
  1190.     effects has always been undefined (see question 5.23).  Don't
  1191.     even try to find out how your compiler implements such things
  1192.     (contrary to the ill-advised exercises in many C textbooks); as
  1193.     K&R wisely point out, "if you don't know _how_ they are done on
  1194.     various machines, that innocence may help to protect you."
  1195.  
  1196.     References: K&R I Sec. 2.12 p. 50; K&R II Sec. 2.12 p. 54; ANSI
  1197.     Sec. 3.3 p. 39; CT&P Sec. 3.7 p. 47; PCS Sec. 9.5 pp. 120-1.
  1198.     (Ignore H&S Sec. 7.12 pp. 190-1, which is obsolete.)
  1199.  
  1200. 4.3:    I've experimented with the code
  1201.  
  1202.         int i = 2;
  1203.         i = i++;
  1204.  
  1205.     on several compilers.  Some gave i the value 2, some gave 3, but
  1206.     one gave 4.  I know the behavior is undefined, but how could it
  1207.     give 4?
  1208.  
  1209. A:    Undefined behavior means _anything_ can happen.  See question
  1210.     5.23.
  1211.  
  1212. 4.4:    People keep saying the behavior is undefined, but I just tried
  1213.     it on an ANSI-conforming compiler, and got the results I
  1214.     expected.
  1215.  
  1216. A:    A compiler may do anything it likes when faced with undefined
  1217.     behavior (and, within limits, with implementation-defined and
  1218.     unspecified behavior), including doing what you expect.  It's
  1219.     unwise to depend on it, though.  See also question 5.18.
  1220.  
  1221. 4.5:    Can I use explicit parentheses to force the order of evaluation
  1222.     I want?  Even if I don't, doesn't precedence dictate it?
  1223.  
  1224. A:    Operator precedence and explicit parentheses impose only a
  1225.     partial ordering on the evaluation of an expression.  Consider
  1226.     the expression
  1227.  
  1228.         f() + g() * h()
  1229.  
  1230.     -- although we know that the multiplication will happen before
  1231.     the addition, there is no telling which of the three functions
  1232.     will be called first.
  1233.  
  1234. 4.6:    But what about the &&, ||, and comma operators?
  1235.     I see code like "if((c = getchar()) == EOF || c == '\n')" ...
  1236.  
  1237. A:    There is a special exception for those operators, (as well as
  1238.     ?: ); each of them does imply a sequence point (i.e. left-to-
  1239.     right evaluation is guaranteed).  Any book on C should make this
  1240.     clear.
  1241.  
  1242.     References: K&R I Sec. 2.6 p. 38, Secs. A7.11-12 pp. 190-1;
  1243.     K&R II Sec. 2.6 p. 41, Secs. A7.14-15 pp. 207-8; ANSI
  1244.     Secs. 3.3.13 p. 52, 3.3.14 p. 52, 3.3.15 p. 53, 3.3.17 p. 55,
  1245.     CT&P Sec. 3.7 pp. 46-7.
  1246.  
  1247. 4.7:    If I'm not using the value of the expression, should I use i++
  1248.     or ++i to increment a variable?
  1249.  
  1250. A:    Since the two forms differ only in the value yielded, they are
  1251.     entirely equivalent when only their side effect is needed.
  1252.  
  1253. 4.8:    Why doesn't the code
  1254.  
  1255.         int a = 1000, b = 1000;
  1256.         long int c = a * b;
  1257.  
  1258.     work?
  1259.  
  1260. A:    Under C's integral promotion rules, the multiplication is
  1261.     carried out using int arithmetic, and the result may overflow
  1262.     and/or be truncated before being assigned to the long int left-
  1263.     hand-side.  Use an explicit cast to force long arithmetic:
  1264.  
  1265.         long int c = (long int)a * b;
  1266.  
  1267.  
  1268. Section 5. ANSI C
  1269.  
  1270. 5.1:    What is the "ANSI C Standard?"
  1271.  
  1272. A:    In 1983, the American National Standards Institute (ANSI)
  1273.     commissioned a committee, X3J11, to standardize the C language.
  1274.     After a long, arduous process, including several widespread
  1275.     public reviews, the committee's work was finally ratified as ANS
  1276.     X3.159-1989, on December 14, 1989, and published in the spring
  1277.     of 1990.  For the most part, ANSI C standardizes existing
  1278.     practice, with a few additions from C++ (most notably function
  1279.     prototypes) and support for multinational character sets
  1280.     (including the much-lambasted trigraph sequences).  The ANSI C
  1281.     standard also formalizes the C run-time library support
  1282.     routines.
  1283.  
  1284.     The published Standard includes a "Rationale," which explains
  1285.     many of its decisions, and discusses a number of subtle points,
  1286.     including several of those covered here.  (The Rationale is "not
  1287.     part of ANSI Standard X3.159-1989, but is included for
  1288.     information only.")
  1289.  
  1290.     The Standard has been adopted as an international standard,
  1291.     ISO/IEC 9899:1990, although the sections are numbered
  1292.     differently (briefly, ANSI sections 2 through 4 correspond
  1293.     roughly to ISO sections 5 through 7), and the Rationale is
  1294.     currently not included.
  1295.  
  1296. 5.2:    How can I get a copy of the Standard?
  1297.  
  1298. A:    ANSI X3.159 has been officially superseded by ISO 9899.  Copies
  1299.     are available in the United States from
  1300.  
  1301.         American National Standards Institute
  1302.         11 W. 42nd St., 13th floor
  1303.         New York, NY  10036  USA
  1304.         (+1) 212 642 4900
  1305.  
  1306.     or
  1307.  
  1308.         Global Engineering Documents
  1309.         2805 McGaw Avenue
  1310.         Irvine, CA  92714  USA
  1311.         (+1) 714 261 1455
  1312.         (800) 854 7179  (U.S. & Canada)
  1313.  
  1314.     In other countries, contact the appropriate national standards
  1315.     body, or ISO in Geneva at:
  1316.  
  1317.         ISO Sales
  1318.         Case Postale 56
  1319.         CH-1211 Geneve 20
  1320.         Switzerland
  1321.  
  1322.     The cost is $130.00 from ANSI or $162.50 from Global.  Copies of
  1323.     the original X3.159 (including the Rationale) are still
  1324.     available at $205.00 from ANSI or $200.50 from Global.  Note
  1325.     that ANSI derives revenues to support its operations from the
  1326.     sale of printed standards, so electronic copies are _not_
  1327.     available.
  1328.  
  1329.     The mistitled _Annotated ANSI C Standard_, with annotations by
  1330.     Herbert Schildt, contains the full text of ISO 9899; it is
  1331.     published by Osborne/McGraw-Hill, ISBN 0-07-881952-0, and sells
  1332.     in the U.S. for approximately $40.  (It has been suggested that
  1333.     the price differential between this work and the official
  1334.     standard reflects the value of the annotations.)
  1335.  
  1336.     The text of the Rationale (not the full Standard) is now
  1337.     available for anonymous ftp from ftp.uu.net (see question 17.12)
  1338.     in directory doc/standards/ansi/X3.159-1989 .  The Rationale has
  1339.     also been printed by Silicon Press, ISBN 0-929306-07-4.
  1340.  
  1341. 5.3:    Does anyone have a tool for converting old-style C programs to
  1342.     ANSI C, or vice versa, or for automatically generating
  1343.     prototypes?
  1344.  
  1345. A:    Two programs, protoize and unprotoize, convert back and forth
  1346.     between prototyped and "old style" function definitions and
  1347.     declarations.  (These programs do _not_ handle full-blown
  1348.     translation between "Classic" C and ANSI C.)  These programs
  1349.     were once patches to the FSF GNU C compiler, gcc, but are now
  1350.     part of the main gcc distribution; look in pub/gnu at
  1351.     prep.ai.mit.edu (18.71.0.38), or at several other FSF archive
  1352.     sites.
  1353.  
  1354.     The unproto program (/pub/unix/unproto5.shar.Z on
  1355.     ftp.win.tue.nl) is a filter which sits between the preprocessor
  1356.     and the next compiler pass, converting most of ANSI C to
  1357.     traditional C on-the-fly.
  1358.  
  1359.     The GNU GhostScript package comes with a little program called
  1360.     ansi2knr.
  1361.  
  1362.     Several prototype generators exist, many as modifications to
  1363.     lint.  Version 3 of CPROTO was posted to comp.sources.misc in
  1364.     March, 1992.  There is another program called "cextract."  See
  1365.     also question 17.12.
  1366.  
  1367.     Finally, are you sure you really need to convert lots of old
  1368.     code to ANSI C?  The old-style function syntax is still
  1369.     acceptable.
  1370.  
  1371. 5.4:    I'm trying to use the ANSI "stringizing" preprocessing operator
  1372.     # to insert the value of a symbolic constant into a message, but
  1373.     it keeps stringizing the macro's name rather than its value.
  1374.  
  1375. A:    You must use something like the following two-step procedure to
  1376.     force the macro to be expanded as well as stringized:
  1377.  
  1378.         #define str(x) #x
  1379.         #define xstr(x) str(x)
  1380.         #define OP plus
  1381.         char *opname = xstr(OP);
  1382.  
  1383.     This sets opname to "plus" rather than "OP".
  1384.  
  1385.     An equivalent circumlocution is necessary with the token-pasting
  1386.     operator ## when the values (rather than the names) of two
  1387.     macros are to be concatenated.
  1388.  
  1389.     References: ANSI Sec. 3.8.3.2, Sec. 3.8.3.5 example p. 93.
  1390.  
  1391. 5.5:    I don't understand why I can't use const values in initializers
  1392.     and array dimensions, as in
  1393.  
  1394.         const int n = 5;
  1395.         int a[n];
  1396.  
  1397. A:    The const qualifier really means "read-only;" an object so
  1398.     qualified is a normal run-time object which cannot (normally) be
  1399.     assigned to.  The value of a const-qualified object is therefore
  1400.     _not_ a constant expression in the full sense of the term.  (C
  1401.     is unlike C++ in this regard.)  When you need a true compile-
  1402.     time constant, use a preprocessor #define.
  1403.  
  1404.     References: ANSI Sec. 3.4 .
  1405.  
  1406. 5.6:    What's the difference between "char const *p" and
  1407.     "char * const p"?
  1408.  
  1409. A:    "char const *p" is a pointer to a constant character (you can't
  1410.     change the character); "char * const p" is a constant pointer to
  1411.     a (variable) character (i.e. you can't change the pointer).
  1412.     (Read these "inside out" to understand them.  See question
  1413.     10.4.)
  1414.  
  1415.     References: ANSI Sec. 3.5.4.1 .
  1416.  
  1417. 5.7:    Why can't I pass a char ** to a function which expects a
  1418.     const char **?
  1419.  
  1420. A:    You can use a pointer-to-T (for any type T) where a pointer-to-
  1421.     const-T is expected, but the rule (an explicit exception) which
  1422.     permits slight mismatches in qualified pointer types is not
  1423.     applied recursively, but only at the top level.
  1424.  
  1425.     You must use explicit casts (e.g. (const char **) in this case)
  1426.     when assigning (or passing) pointers which have qualifier
  1427.     mismatches at other than the first level of indirection.
  1428.  
  1429.     References: ANSI Sec. 3.1.2.6 p. 26, Sec. 3.3.16.1 p. 54,
  1430.     Sec. 3.5.3 p. 65.
  1431.  
  1432. 5.8:    My ANSI compiler complains about a mismatch when it sees
  1433.  
  1434.         extern int func(float);
  1435.  
  1436.         int func(x)
  1437.         float x;
  1438.         {...
  1439.  
  1440. A:    You have mixed the new-style prototype declaration
  1441.     "extern int func(float);" with the old-style definition
  1442.     "int func(x) float x;".  It is usually safe to mix the two
  1443.     styles (see question 5.9), but not in this case.  Old C (and
  1444.     ANSI C, in the absence of prototypes, and in variable-length
  1445.     argument lists) "widens" certain arguments when they are passed
  1446.     to functions.  floats are promoted to double, and characters and
  1447.     short integers are promoted to ints.  (For old-style function
  1448.     definitions, the values are automatically converted back to the
  1449.     corresponding narrower types within the body of the called
  1450.     function, if they are declared that way there.)
  1451.  
  1452.     This problem can be fixed either by using new-style syntax
  1453.     consistently in the definition:
  1454.  
  1455.         int func(float x) { ... }
  1456.  
  1457.     or by changing the new-style prototype declaration to match the
  1458.     old-style definition:
  1459.  
  1460.         extern int func(double);
  1461.  
  1462.     (In this case, it would be clearest to change the old-style
  1463.     definition to use double as well, as long as the address of that
  1464.     parameter is not taken.)
  1465.  
  1466.     It may also be safer to avoid "narrow" (char, short int, and
  1467.     float) function arguments and return types.
  1468.  
  1469.     References: ANSI Sec. 3.3.2.2 .
  1470.  
  1471. 5.9:    Can you mix old-style and new-style function syntax?
  1472.  
  1473. A:    Doing so is perfectly legal, as long as you're careful (see
  1474.     especially question 5.8).  Note however that old-style syntax is
  1475.     marked as obsolescent, and support for it may be removed some
  1476.     day.
  1477.  
  1478.     References: ANSI Secs. 3.7.1, 3.9.5 .
  1479.  
  1480. 5.10:    Why does the declaration
  1481.  
  1482.         extern f(struct x {int s;} *p);
  1483.  
  1484.     give me an obscure warning message about "struct x introduced in
  1485.     prototype scope"?
  1486.  
  1487. A:    In a quirk of C's normal block scoping rules, a struct declared
  1488.     only within a prototype cannot be compatible with other structs
  1489.     declared in the same source file, nor can the struct tag be used
  1490.     later as you'd expect (it goes out of scope at the end of the
  1491.     prototype).
  1492.  
  1493.     To resolve the problem, precede the prototype with the vacuous-
  1494.     looking declaration
  1495.  
  1496.         struct x;
  1497.  
  1498.     , which will reserve a place at file scope for struct x's
  1499.     definition, which will be completed by the struct declaration
  1500.     within the prototype.
  1501.  
  1502.     References: ANSI Sec. 3.1.2.1 p. 21, Sec. 3.1.2.6 p. 26,
  1503.     Sec. 3.5.2.3 p. 63.
  1504.  
  1505. 5.11:    I'm getting strange syntax errors inside code which I've
  1506.     #ifdeffed out.
  1507.  
  1508. A:    Under ANSI C, the text inside a "turned off" #if, #ifdef, or
  1509.     #ifndef must still consist of "valid preprocessing tokens."
  1510.     This means that there must be no unterminated comments or quotes
  1511.     (note particularly that an apostrophe within a contracted word
  1512.     could look like the beginning of a character constant), and no
  1513.     newlines inside quotes.  Therefore, natural-language comments
  1514.     and pseudocode should always be written between the "official"
  1515.     comment delimiters /* and */.  (But see also question 17.14, and
  1516.     6.7.)
  1517.  
  1518.     References: ANSI Sec. 2.1.1.2 p. 6, Sec. 3.1 p. 19 line 37.
  1519.  
  1520. 5.12:    Can I declare main as void, to shut off these annoying "main
  1521.     returns no value" messages?  (I'm calling exit(), so main
  1522.     doesn't return.)
  1523.  
  1524. A:    No.  main must be declared as returning an int, and as taking
  1525.     either zero or two arguments (of the appropriate type).  If
  1526.     you're calling exit() but still getting warnings, you'll have to
  1527.     insert a redundant return statement (or use some kind of
  1528.     "notreached" directive, if available).
  1529.  
  1530.     Declaring a function as void does not merely silence warnings;
  1531.     it may also result in a different function call/return sequence,
  1532.     incompatible with what the caller (in main's case, the C run-
  1533.     time startup code) expects.
  1534.  
  1535.     References: ANSI Sec. 2.1.2.2.1 pp. 7-8.
  1536.  
  1537. 5.13:    Is exit(status) truly equivalent to returning status from main?
  1538.  
  1539. A:    Essentially, except under a few older, nonconforming systems,
  1540.     and unless data local to main might be needed during cleanup
  1541.     (due perhaps to a setbuf or atexit call).
  1542.  
  1543.     References: ANSI Sec. 2.1.2.2.3 p. 8.
  1544.  
  1545. 5.14:    Why does the ANSI Standard not guarantee more than six monocase
  1546.     characters of external identifier significance?
  1547.  
  1548. A:    The problem is older linkers which are neither under the control
  1549.     of the ANSI standard nor the C compiler developers on the
  1550.     systems which have them.  The limitation is only that
  1551.     identifiers be _significant_ in the first six characters, not
  1552.     that they be restricted to six characters in length.  This
  1553.     limitation is annoying, but certainly not unbearable, and is
  1554.     marked in the Standard as "obsolescent," i.e. a future revision
  1555.     will likely relax it.
  1556.  
  1557.     This concession to current, restrictive linkers really had to be
  1558.     made, no matter how vehemently some people oppose it.  (The
  1559.     Rationale notes that its retention was "most painful.")  If you
  1560.     disagree, or have thought of a trick by which a compiler
  1561.     burdened with a restrictive linker could present the C
  1562.     programmer with the appearance of more significance in external
  1563.     identifiers, read the excellently-worded section 3.1.2 in the
  1564.     X3.159 Rationale (see question 5.1), which discusses several
  1565.     such schemes and explains why they could not be mandated.
  1566.  
  1567.     References: ANSI Sec. 3.1.2 p. 21, Sec. 3.9.1 p. 96, Rationale
  1568.     Sec. 3.1.2 pp. 19-21.
  1569.  
  1570. 5.15:    What is the difference between memcpy and memmove?
  1571.  
  1572. A:    memmove offers guaranteed behavior if the source and destination
  1573.     arguments overlap.  memcpy makes no such guarantee, and may
  1574.     therefore be more efficiently implementable.  When in doubt,
  1575.     it's safer to use memmove.
  1576.  
  1577.     References: ANSI Secs. 4.11.2.1, 4.11.2.2, Rationale
  1578.     Sec. 4.11.2 .
  1579.  
  1580. 5.16:    My compiler is rejecting the simplest possible test programs,
  1581.     with all kinds of syntax errors.
  1582.  
  1583. A:    Perhaps it is a pre-ANSI compiler, unable to accept function
  1584.     prototypes and the like.  See also questions 5.17 and 17.2.
  1585.  
  1586. 5.17:    Why are some ANSI/ISO Standard library routines showing up as
  1587.     undefined, even though I've got an ANSI compiler?
  1588.  
  1589. A:    It's not unusual to have a compiler available which accepts ANSI
  1590.     syntax, but not to have ANSI-compatible header files or run-time
  1591.     libraries installed.  See also questions 5.16 and 17.2.
  1592.  
  1593. 5.18:    Why won't the Frobozz Magic C Compiler, which claims to be ANSI
  1594.     compliant, accept this code?  I know that the code is ANSI,
  1595.     because gcc accepts it.
  1596.  
  1597. A:    Most compilers support a few non-Standard extensions, gcc more
  1598.     so than most.  Are you sure that the code being rejected doesn't
  1599.     rely on such an extension?  It is usually a bad idea to perform
  1600.     experiments with a particular compiler to determine properties
  1601.     of a language; the applicable standard may permit variations, or
  1602.     the compiler may be wrong.  See also question 4.4.
  1603.  
  1604. 5.19:    Why can't I perform arithmetic on a void * pointer?
  1605.  
  1606. A:    The compiler doesn't know the size of the pointed-to objects.
  1607.     Before performing arithmetic, cast the pointer either to char *
  1608.     or to the type you're trying to manipulate.
  1609.  
  1610. 5.20:    Is char a[3] = "abc"; legal?  What does it mean?
  1611.  
  1612. A:    It is legal in ANSI C (and perhaps in a few pre-ANSI systems),
  1613.     though questionably useful.  It declares an array of size three,
  1614.     initialized with the three characters 'a', 'b', and 'c', without
  1615.     the usual terminating '\0' character; the array is therefore not
  1616.     a true C string and cannot be used with strcpy, printf %s, etc.
  1617.  
  1618.     References: ANSI Sec. 3.5.7 pp. 72-3.
  1619.  
  1620. 5.21:    What are #pragmas and what are they good for?
  1621.  
  1622. A:    The #pragma directive provides a single, well-defined "escape
  1623.     hatch" which can be used for all sorts of implementation-
  1624.     specific controls and extensions: source listing control,
  1625.     structure packing, warning suppression (like the old lint
  1626.     /* NOTREACHED */ comments), etc.
  1627.  
  1628.     References: ANSI Sec. 3.8.6 .
  1629.  
  1630. 5.22:    What does #pragma once mean?  I found it in some header files.
  1631.  
  1632. A:    It is an extension implemented by some preprocessors to help
  1633.     make header files idempotent; it is essentially equivalent to
  1634.     the #ifndef trick mentioned in question 6.4.
  1635.  
  1636. 5.23:    People seem to make a point of distinguishing between
  1637.     implementation-defined, unspecified, and undefined behavior.
  1638.     What's the difference?
  1639.  
  1640. A:    Briefly: implementation-defined means that an implementation
  1641.     must choose some behavior and document it.  Unspecified means
  1642.     that an implementation should choose some behavior, but need not
  1643.     document it.  Undefined means that absolutely anything might
  1644.     happen.  In no case does the Standard impose requirements; in
  1645.     the first two cases it occasionally suggests (and may require a
  1646.     choice from among) a small set of likely behaviors.
  1647.  
  1648.     If you're interested in writing portable code, you can ignore
  1649.     the distinctions, as you'll want to avoid code that depends on
  1650.     any of the three behaviors.
  1651.  
  1652.     References: ANSI Sec. 1.6, especially the Rationale.
  1653.  
  1654.  
  1655. Section 6. C Preprocessor
  1656.  
  1657. 6.1:    How can I write a generic macro to swap two values?
  1658.  
  1659. A:    There is no good answer to this question.  If the values are
  1660.     integers, a well-known trick using exclusive-OR could perhaps be
  1661.     used, but it will not work for floating-point values or
  1662.     pointers, or if the two values are the same variable (and the
  1663.     "obvious" supercompressed implementation for integral types
  1664.     a^=b^=a^=b is in fact illegal due to multiple side-effects; see
  1665.     questions 4.1 and 4.2).  If the macro is intended to be used on
  1666.     values of arbitrary type (the usual goal), it cannot use a
  1667.     temporary, since it does not know what type of temporary it
  1668.     needs, and standard C does not provide a typeof operator.
  1669.  
  1670.     The best all-around solution is probably to forget about using a
  1671.     macro, unless you're willing to pass in the type as a third
  1672.     argument.
  1673.  
  1674. 6.2:    I have some old code that tries to construct identifiers with a
  1675.     macro like
  1676.  
  1677.         #define Paste(a, b) a/**/b
  1678.  
  1679.     but it doesn't work any more.
  1680.  
  1681. A:    That comments disappeared entirely and could therefore be used
  1682.     for token pasting was an undocumented feature of some early
  1683.     preprocessor implementations, notably Reiser's.  ANSI affirms
  1684.     (as did K&R) that comments are replaced with white space.
  1685.     However, since the need for pasting tokens was demonstrated and
  1686.     real, ANSI introduced a well-defined token-pasting operator, ##,
  1687.     which can be used like this:
  1688.  
  1689.         #define Paste(a, b) a##b
  1690.  
  1691.     (See also question 5.4.)
  1692.  
  1693.     References: ANSI Sec. 3.8.3.3 p. 91, Rationale pp. 66-7.
  1694.  
  1695. 6.3:    What's the best way to write a multi-statement cpp macro?
  1696.  
  1697. A:    The usual goal is to write a macro that can be invoked as if it
  1698.     were a single function-call statement.  This means that the
  1699.     "caller" will be supplying the final semicolon, so the macro
  1700.     body should not.  The macro body cannot be a simple brace-
  1701.     delineated compound statement, because syntax errors would
  1702.     result if it were invoked (apparently as a single statement, but
  1703.     with a resultant extra semicolon) as the if branch of an if/else
  1704.     statement with an explicit else clause.
  1705.  
  1706.     The traditional solution is to use
  1707.  
  1708.         #define Func() do { \
  1709.             /* declarations */ \
  1710.             stmt1; \
  1711.             stmt2; \
  1712.             /* ... */ \
  1713.             } while(0)    /* (no trailing ; ) */
  1714.  
  1715.     When the "caller" appends a semicolon, this expansion becomes a
  1716.     single statement regardless of context.  (An optimizing compiler
  1717.     will remove any "dead" tests or branches on the constant
  1718.     condition 0, although lint may complain.)
  1719.  
  1720.     If all of the statements in the intended macro are simple
  1721.     expressions, with no declarations or loops, another technique is
  1722.     to write a single, parenthesized expression using one or more
  1723.     comma operators.  (See the example under question 6.10 below.
  1724.     This technique also allows a value to be "returned.")
  1725.  
  1726.     References: CT&P Sec. 6.3 pp. 82-3.
  1727.  
  1728. 6.4:    Is it acceptable for one header file to #include another?
  1729.  
  1730. A:    It's a question of style, and thus receives considerable debate.
  1731.     Many people believe that "nested #include files" are to be
  1732.     avoided: the prestigious Indian Hill Style Guide (see question
  1733.     14.3) disparages them; they can make it harder to find relevant
  1734.     definitions; they can lead to multiple-declaration errors if a
  1735.     file is #included twice; and they make manual Makefile
  1736.     maintenance very difficult.  On the other hand, they make it
  1737.     possible to use header files in a modular way (a header file
  1738.     #includes what it needs itself, rather than requiring each
  1739.     #includer to do so, a requirement that can lead to intractable
  1740.     headaches); a tool like grep (or a tags file) makes it easy to
  1741.     find definitions no matter where they are; a popular trick:
  1742.  
  1743.         #ifndef HEADERUSED
  1744.         #define HEADERUSED
  1745.         ...header file contents...
  1746.         #endif
  1747.  
  1748.     makes a header file "idempotent" so that it can safely be
  1749.     #included multiple times; and automated Makefile maintenance
  1750.     tools (which are a virtual necessity in large projects anyway)
  1751.     handle dependency generation in the face of nested #include
  1752.     files easily.  See also section 14.
  1753.  
  1754. 6.5:    Does the sizeof operator work in preprocessor #if directives?
  1755.  
  1756. A:    No.  Preprocessing happens during an earlier pass of
  1757.     compilation, before type names have been parsed.  Consider using
  1758.     the predefined constants in ANSI's <limits.h>, if applicable, or
  1759.     a "configure" script, instead.  (Better yet, try to write code
  1760.     which is inherently insensitive to type sizes.)
  1761.  
  1762.     References: ANSI Sec. 2.1.1.2 pp. 6-7, Sec. 3.8.1 p. 87
  1763.     footnote 83.
  1764.  
  1765. 6.6:    How can I use a preprocessor #if expression to tell if a machine
  1766.     is big-endian or little-endian?
  1767.  
  1768. A:    You probably can't.  (Preprocessor arithmetic uses only long
  1769.     ints, and there is no concept of addressing.)  Are you sure you
  1770.     need to know the machine's endianness explicitly?  Usually it's
  1771.     better to write code which doesn't care.
  1772.  
  1773. 6.7:    I've got this tricky processing I want to do at compile time and
  1774.     I can't figure out a way to get cpp to do it.
  1775.  
  1776. A:    cpp is not intended as a general-purpose preprocessor.  Rather
  1777.     than forcing it to do something inappropriate, consider writing
  1778.     your own little special-purpose preprocessing tool, instead.
  1779.     You can easily get a utility like make(1) to run it for you
  1780.     automatically.
  1781.  
  1782.     If you are trying to preprocess something other than C, consider
  1783.     using a general-purpose preprocessor (such as m4).
  1784.  
  1785. 6.8:    I inherited some code which contains far too many #ifdef's for
  1786.     my taste.  How can I preprocess the code to leave only one
  1787.     conditional compilation set, without running it through cpp and
  1788.     expanding all of the #include's and #define's as well?
  1789.  
  1790. A:    There are programs floating around called unifdef, rmifdef, and
  1791.     scpp which do exactly this.  (See question 17.12.)
  1792.  
  1793. 6.9:    How can I list all of the pre#defined identifiers?
  1794.  
  1795. A:    There's no standard way, although it is a frequent need.  The
  1796.     most expedient way is probably to extract printable strings from
  1797.     the compiler or preprocessor executable with something like the
  1798.     Unix strings(1) utility.
  1799.  
  1800. 6.10:    How can I write a cpp macro which takes a variable number of
  1801.     arguments?
  1802.  
  1803. A:    One popular trick is to define the macro with a single argument,
  1804.     and call it with a double set of parentheses, which appear to
  1805.     the preprocessor to indicate a single argument:
  1806.  
  1807.         #define DEBUG(args) (printf("DEBUG: "), printf args)
  1808.  
  1809.         if(n != 0) DEBUG(("n is %d\n", n));
  1810.  
  1811.     The obvious disadvantage is that the caller must always remember
  1812.     to use the extra parentheses.  Other solutions are to use
  1813.     different macros (DEBUG1, DEBUG2, etc.) depending on the number
  1814.     of arguments, or to play games with commas:
  1815.  
  1816.         #define DEBUG(args) (printf("DEBUG: "), printf(args))
  1817.         #define _ ,
  1818.         DEBUG("i = %d" _ i)
  1819.  
  1820.     It is often better to use a bona-fide function, which can take a
  1821.     variable number of arguments in a well-defined way.  See
  1822.     questions 7.1 and 7.2.
  1823.  
  1824.  
  1825. Section 7. Variable-Length Argument Lists
  1826.  
  1827. 7.1:    How can I write a function that takes a variable number of
  1828.     arguments?
  1829.  
  1830. A:    Use the <stdarg.h> header (or, if you must, the older
  1831.     <varargs.h>).
  1832.  
  1833.     Here is a function which concatenates an arbitrary number of
  1834.     strings into malloc'ed memory:
  1835.  
  1836.         #include <stdlib.h>        /* for malloc, NULL, size_t */
  1837.         #include <stdarg.h>        /* for va_ stuff */
  1838.         #include <string.h>        /* for strcat et al */
  1839.  
  1840.         char *vstrcat(char *first, ...)
  1841.         {
  1842.             size_t len = 0;
  1843.             char *retbuf;
  1844.             va_list argp;
  1845.             char *p;
  1846.  
  1847.             if(first == NULL)
  1848.                 return NULL;
  1849.  
  1850.             len = strlen(first);
  1851.  
  1852.             va_start(argp, first);
  1853.  
  1854.             while((p = va_arg(argp, char *)) != NULL)
  1855.                 len += strlen(p);
  1856.  
  1857.             va_end(argp);
  1858.  
  1859.             retbuf = malloc(len + 1);    /* +1 for trailing \0 */
  1860.  
  1861.             if(retbuf == NULL)
  1862.                 return NULL;        /* error */
  1863.  
  1864.             (void)strcpy(retbuf, first);
  1865.  
  1866.             va_start(argp, first);
  1867.  
  1868.             while((p = va_arg(argp, char *)) != NULL)
  1869.                 (void)strcat(retbuf, p);
  1870.  
  1871.             va_end(argp);
  1872.  
  1873.             return retbuf;
  1874.         }
  1875.  
  1876.     Usage is something like
  1877.  
  1878.         char *str = vstrcat("Hello, ", "world!", (char *)NULL);
  1879.  
  1880.     Note the cast on the last argument.  (Also note that the caller
  1881.     must free the returned, malloc'ed storage.)
  1882.  
  1883.     Under a pre-ANSI compiler, rewrite the function definition
  1884.     without a prototype ("char *vstrcat(first) char *first; {"),
  1885.     include <stdio.h> rather than <stdlib.h>, add "extern
  1886.     char *malloc();", and use int instead of size_t.  You may also
  1887.     have to delete the (void) casts, and use the older varargs
  1888.     package instead of stdarg.  See the next question for hints.
  1889.  
  1890.     Remember that in variable-length argument lists, function
  1891.     prototypes do not supply parameter type information; therefore,
  1892.     default argument promotions apply (see question 5.8), and null
  1893.     pointer arguments must be typed explicitly (see question 1.2).
  1894.  
  1895.     References: K&R II Sec. 7.3 p. 155, Sec. B7 p. 254; H&S
  1896.     Sec. 13.4 pp. 286-9; ANSI Secs. 4.8 through 4.8.1.3 .
  1897.  
  1898. 7.2:    How can I write a function that takes a format string and a
  1899.     variable number of arguments, like printf, and passes them to
  1900.     printf to do most of the work?
  1901.  
  1902. A:    Use vprintf, vfprintf, or vsprintf.
  1903.  
  1904.     Here is an "error" routine which prints an error message,
  1905.     preceded by the string "error: " and terminated with a newline:
  1906.  
  1907.         #include <stdio.h>
  1908.         #include <stdarg.h>
  1909.  
  1910.         void
  1911.         error(char *fmt, ...)
  1912.         {
  1913.             va_list argp;
  1914.             fprintf(stderr, "error: ");
  1915.             va_start(argp, fmt);
  1916.             vfprintf(stderr, fmt, argp);
  1917.             va_end(argp);
  1918.             fprintf(stderr, "\n");
  1919.         }
  1920.  
  1921.     To use the older <varargs.h> package, instead of <stdarg.h>,
  1922.     change the function header to:
  1923.  
  1924.         void error(va_alist)
  1925.         va_dcl
  1926.         {
  1927.             char *fmt;
  1928.  
  1929.     change the va_start line to
  1930.  
  1931.         va_start(argp);
  1932.  
  1933.     and add the line
  1934.  
  1935.         fmt = va_arg(argp, char *);
  1936.  
  1937.     between the calls to va_start and vfprintf.  (Note that there is
  1938.     no semicolon after va_dcl.)
  1939.  
  1940.     References: K&R II Sec. 8.3 p. 174, Sec. B1.2 p. 245; H&S
  1941.     Sec. 17.12 p. 337; ANSI Secs. 4.9.6.7, 4.9.6.8, 4.9.6.9 .
  1942.  
  1943. 7.3:    How can I discover how many arguments a function was actually
  1944.     called with?
  1945.  
  1946. A:    This information is not available to a portable program.  Some
  1947.     old systems provided a nonstandard nargs() function, but its use
  1948.     was always questionable, since it typically returned the number
  1949.     of words passed, not the number of arguments.  (Structures and
  1950.     floating point values are usually passed as several words.)
  1951.  
  1952.     Any function which takes a variable number of arguments must be
  1953.     able to determine from the arguments themselves how many of them
  1954.     there are.  printf-like functions do this by looking for
  1955.     formatting specifiers (%d and the like) in the format string
  1956.     (which is why these functions fail badly if the format string
  1957.     does not match the argument list).  Another common technique
  1958.     (useful when the arguments are all of the same type) is to use a
  1959.     sentinel value (often 0, -1, or an appropriately-cast null
  1960.     pointer) at the end of the list (see the execl and vstrcat
  1961.     examples under questions 1.2 and 7.1 above).
  1962.  
  1963. 7.4:    I can't get the va_arg macro to pull in an argument of type
  1964.     pointer-to-function.
  1965.  
  1966. A:    The type-rewriting games which the va_arg macro typically plays
  1967.     are stymied by overly-complicated types such as pointer-to-
  1968.     function.  If you use a typedef for the function pointer type,
  1969.     however, all will be well.
  1970.  
  1971.     References: ANSI Sec. 4.8.1.2 p. 124.
  1972.  
  1973. 7.5:    How can I write a function which takes a variable number of
  1974.     arguments and passes them to some other function (which takes a
  1975.     variable number of arguments)?
  1976.  
  1977. A:    In general, you cannot.  You must provide a version of that
  1978.     other function which accepts a va_list pointer, as does vfprintf
  1979.     in the example above.  If the arguments must be passed directly
  1980.     as actual arguments (not indirectly through a va_list pointer)
  1981.     to another function which is itself variadic (for which you do
  1982.     not have the option of creating an alternate, va_list-accepting
  1983.     version) no portable solution is possible.  (The problem can be
  1984.     solved by resorting to machine-specific assembly language.)
  1985.  
  1986. 7.6:    How can I call a function with an argument list built up at run
  1987.     time?
  1988.  
  1989. A:    There is no guaranteed or portable way to do this.  If you're
  1990.     curious, ask this list's editor, who has a few wacky ideas you
  1991.     could try...  (See also question 16.11.)
  1992.  
  1993.  
  1994. Section 8. Boolean Expressions and Variables
  1995.  
  1996. 8.1:    What is the right type to use for boolean values in C?  Why
  1997.     isn't it a standard type?  Should #defines or enums be used for
  1998.     the true and false values?
  1999.  
  2000. A:    C does not provide a standard boolean type, because picking one
  2001.     involves a space/time tradeoff which is best decided by the
  2002.     programmer.  (Using an int for a boolean may be faster, while
  2003.     using char may save data space.)
  2004.  
  2005.     The choice between #defines and enums is arbitrary and not
  2006.     terribly interesting (see also question 9.1).  Use any of
  2007.  
  2008.         #define TRUE  1            #define YES 1
  2009.         #define FALSE 0            #define NO  0
  2010.  
  2011.         enum bool {false, true};    enum bool {no, yes};
  2012.  
  2013.     or use raw 1 and 0, as long as you are consistent within one
  2014.     program or project.  (An enum may be preferable if your debugger
  2015.     expands enum values when examining variables.)
  2016.  
  2017.     Some people prefer variants like
  2018.  
  2019.         #define TRUE (1==1)
  2020.         #define FALSE (!TRUE)
  2021.  
  2022.     or define "helper" macros such as
  2023.  
  2024.         #define Istrue(e) ((e) != 0)
  2025.  
  2026.     These don't buy anything (see question 8.2 below; see also
  2027.     question 1.6).
  2028.  
  2029. 8.2:    Isn't #defining TRUE to be 1 dangerous, since any nonzero value
  2030.     is considered "true" in C?  What if a built-in boolean or
  2031.     relational operator "returns" something other than 1?
  2032.  
  2033. A:    It is true (sic) that any nonzero value is considered true in C,
  2034.     but this applies only "on input", i.e. where a boolean value is
  2035.     expected.  When a boolean value is generated by a built-in
  2036.     operator, it is guaranteed to be 1 or 0.  Therefore, the test
  2037.  
  2038.         if((a == b) == TRUE)
  2039.  
  2040.     will work as expected (as long as TRUE is 1), but it is
  2041.     obviously silly.  In general, explicit tests against TRUE and
  2042.     FALSE are undesirable, because some library functions (notably
  2043.     isupper, isalpha, etc.) return, on success, a nonzero value
  2044.     which is _not_ necessarily 1.  (Besides, if you believe that
  2045.     "if((a == b) == TRUE)" is an improvement over "if(a == b)", why
  2046.     stop there?  Why not use "if(((a == b) == TRUE) == TRUE)"?)  A
  2047.     good rule of thumb is to use TRUE and FALSE (or the like) only
  2048.     for assignment to a Boolean variable, or as the return value
  2049.     from a Boolean function, never in a comparison.
  2050.  
  2051.     The preprocessor macros TRUE and FALSE are used for code
  2052.     readability, not because the underlying values might ever
  2053.     change.  (See also questions 1.7 and 1.9.)
  2054.  
  2055.     References: K&R I Sec. 2.7 p. 41; K&R II Sec. 2.6 p. 42,
  2056.     Sec. A7.4.7 p. 204, Sec. A7.9 p. 206; ANSI Secs. 3.3.3.3, 3.3.8,
  2057.     3.3.9, 3.3.13, 3.3.14, 3.3.15, 3.6.4.1, 3.6.5; Achilles and the
  2058.     Tortoise.
  2059.  
  2060.  
  2061. Section 9. Structs, Enums, and Unions
  2062.  
  2063. 9.1:    What is the difference between an enum and a series of
  2064.     preprocessor #defines?
  2065.  
  2066. A:    At the present time, there is little difference.  Although many
  2067.     people might have wished otherwise, the ANSI standard says that
  2068.     enumerations may be freely intermixed with integral types,
  2069.     without errors.  (If such intermixing were disallowed without
  2070.     explicit casts, judicious use of enums could catch certain
  2071.     programming errors.)
  2072.  
  2073.     Some advantages of enums are that the numeric values are
  2074.     automatically assigned, that a debugger may be able to display
  2075.     the symbolic values when enum variables are examined, and that
  2076.     they obey block scope.  (A compiler may also generate nonfatal
  2077.     warnings when enums and ints are indiscriminately mixed, since
  2078.     doing so can still be considered bad style even though it is not
  2079.     strictly illegal).  A disadvantage is that the programmer has
  2080.     little control over the size (or over those nonfatal warnings).
  2081.  
  2082.     References: K&R II Sec. 2.3 p. 39, Sec. A4.2 p. 196; H&S
  2083.     Sec. 5.5 p. 100; ANSI Secs. 3.1.2.5, 3.5.2, 3.5.2.2 .
  2084.  
  2085. 9.2:    I heard that structures could be assigned to variables and
  2086.     passed to and from functions, but K&R I says not.
  2087.  
  2088. A:    What K&R I said was that the restrictions on struct operations
  2089.     would be lifted in a forthcoming version of the compiler, and in
  2090.     fact struct assignment and passing were fully functional in
  2091.     Ritchie's compiler even as K&R I was being published.  Although
  2092.     a few early C compilers lacked struct assignment, all modern
  2093.     compilers support it, and it is part of the ANSI C standard, so
  2094.     there should be no reluctance to use it.
  2095.  
  2096.     References: K&R I Sec. 6.2 p. 121; K&R II Sec. 6.2 p. 129; H&S
  2097.     Sec. 5.6.2 p. 103; ANSI Secs. 3.1.2.5, 3.2.2.1, 3.3.16 .
  2098.  
  2099. 9.3:    How does struct passing and returning work?
  2100.  
  2101. A:    When structures are passed as arguments to functions, the entire
  2102.     struct is typically pushed on the stack, using as many words as
  2103.     are required.  (Programmers often choose to use pointers to
  2104.     structures instead, precisely to avoid this overhead.)
  2105.  
  2106.     Structures are often returned from functions in a location
  2107.     pointed to by an extra, compiler-supplied "hidden" argument to
  2108.     the function.  Some older compilers used a special, static
  2109.     location for structure returns, although this made struct-valued
  2110.     functions nonreentrant, which ANSI C disallows.
  2111.  
  2112.     References: ANSI Sec. 2.2.3 p. 13.
  2113.  
  2114. 9.4:    The following program works correctly, but it dumps core after
  2115.     it finishes.  Why?
  2116.  
  2117.         struct list
  2118.             {
  2119.             char *item;
  2120.             struct list *next;
  2121.             }
  2122.  
  2123.         /* Here is the main program. */
  2124.  
  2125.         main(argc, argv)
  2126.         ...
  2127.  
  2128. A:    A missing semicolon causes the compiler to believe that main
  2129.     returns a structure.  (The connection is hard to see because of
  2130.     the intervening comment.)  Since struct-valued functions are
  2131.     usually implemented by adding a hidden return pointer, the
  2132.     generated code for main() tries to accept three arguments,
  2133.     although only two are passed (in this case, by the C start-up
  2134.     code).  See also question 17.21.
  2135.  
  2136.     References: CT&P Sec. 2.3 pp. 21-2.
  2137.  
  2138. 9.5:    Why can't you compare structs?
  2139.  
  2140. A:    There is no reasonable way for a compiler to implement struct
  2141.     comparison which is consistent with C's low-level flavor.  A
  2142.     byte-by-byte comparison could be invalidated by random bits
  2143.     present in unused "holes" in the structure (such padding is used
  2144.     to keep the alignment of later fields correct; see questions
  2145.     9.10 and 9.11).  A field-by-field comparison would require
  2146.     unacceptable amounts of repetitive, in-line code for large
  2147.     structures.
  2148.  
  2149.     If you want to compare two structures, you must write your own
  2150.     function to do so.  C++ would let you arrange for the ==
  2151.     operator to map to your function.
  2152.  
  2153.     References: K&R II Sec. 6.2 p. 129; H&S Sec. 5.6.2 p. 103; ANSI
  2154.     Rationale Sec. 3.3.9 p. 47.
  2155.  
  2156. 9.6:    How can I read/write structs from/to data files?
  2157.  
  2158. A:    It is relatively straightforward to write a struct out using
  2159.     fwrite:
  2160.  
  2161.         fwrite((char *)&somestruct, sizeof(somestruct), 1, fp);
  2162.  
  2163.     and a corresponding fread invocation can read it back in.
  2164.     However, data files so written will _not_ be very portable (see
  2165.     questions 9.11 and 17.3).  Note also that on many systems you
  2166.     must use the "b" flag when fopening the files.
  2167.  
  2168. 9.7:    I came across some code that declared a structure like this:
  2169.  
  2170.         struct name
  2171.             {
  2172.             int namelen;
  2173.             char name[1];
  2174.             };
  2175.  
  2176.     and then did some tricky allocation to make the name array act
  2177.     like it had several elements.  Is this legal and/or portable?
  2178.  
  2179. A:    This technique is popular, although Dennis Ritchie has called it
  2180.     "unwarranted chumminess with the C implementation."  An ANSI
  2181.     Interpretation Ruling has deemed it (more precisely, access
  2182.     beyond the declared size of the name field) to be not strictly
  2183.     conforming, although a thorough treatment of the arguments
  2184.     surrounding the legality of the technique is beyond the scope of
  2185.     this list.  It seems, however, to be portable to all known
  2186.     implementations.  (Compilers which check array bounds carefully
  2187.     might issue warnings.)
  2188.  
  2189.     To be on the safe side, it may be preferable to declare the
  2190.     variable-size element very large, rather than very small; in the
  2191.     case of the above example:
  2192.  
  2193.         ...
  2194.         char name[MAXSIZE];
  2195.         ...
  2196.  
  2197.     where MAXSIZE is larger than any name which will be stored.
  2198.     (The trick so modified is said to be in conformance with the
  2199.     Standard.)
  2200.  
  2201.     References: ANSI Rationale Sec. 3.5.4.2 pp. 54-5.
  2202.  
  2203. 9.8:    How can I determine the byte offset of a field within a
  2204.     structure?
  2205.  
  2206. A:    ANSI C defines the offsetof macro, which should be used if
  2207.     available; see <stddef.h>.  If you don't have it, a suggested
  2208.     implementation is
  2209.  
  2210.         #define offsetof(type, mem) ((size_t) \
  2211.             ((char *)&((type *) 0)->mem - (char *)((type *) 0)))
  2212.  
  2213.     This implementation is not 100% portable; some compilers may
  2214.     legitimately refuse to accept it.
  2215.  
  2216.     See the next question for a usage hint.
  2217.  
  2218.     References: ANSI Sec. 4.1.5, Rationale Sec. 3.5.4.2 p. 55.
  2219.  
  2220. 9.9:    How can I access structure fields by name at run time?
  2221.  
  2222. A:    Build a table of names and offsets, using the offsetof() macro.
  2223.     The offset of field b in struct a is
  2224.  
  2225.         offsetb = offsetof(struct a, b)
  2226.  
  2227.     If structp is a pointer to an instance of this structure, and b
  2228.     is an int field with offset as computed above, b's value can be
  2229.     set indirectly with
  2230.  
  2231.         *(int *)((char *)structp + offsetb) = value;
  2232.  
  2233. 9.10:    Why does sizeof report a larger size than I expect for a
  2234.     structure type, as if there was padding at the end?
  2235.  
  2236. A:    Structures may have this padding (as well as internal padding;
  2237.     see also question 9.5), so that alignment properties will be
  2238.     preserved when an array of contiguous structures is allocated.
  2239.  
  2240. 9.11:    My compiler is leaving holes in structures, which is wasting
  2241.     space and preventing "binary" I/O to external data files.  Can I
  2242.     turn off the padding, or otherwise control the alignment of
  2243.     structs?
  2244.  
  2245. A:    Your compiler may provide an extension to give you this control
  2246.     (perhaps a #pragma), but there is no standard method.  See also
  2247.     question 17.3.
  2248.  
  2249. 9.12:    Can I initialize unions?
  2250.  
  2251. A:    ANSI Standard C allows an initializer for the first member of a
  2252.     union.  There is no standard way of initializing the other
  2253.     members (nor, under a pre-ANSI compiler, is there generally any
  2254.     way of initializing any of them).
  2255.  
  2256. 9.13:    How can I pass constant values to routines which accept struct
  2257.     arguments?
  2258.  
  2259. A:    C has no way of generating anonymous struct values.  You will
  2260.     have to use a temporary struct variable.
  2261.  
  2262.  
  2263. Section 10. Declarations
  2264.  
  2265. 10.1:    How do you decide which integer type to use?
  2266.  
  2267. A:    If you might need large values (above 32767 or below -32767),
  2268.     use long.  Otherwise, if space is very important (there are
  2269.     large arrays or many structures), use short.  Otherwise, use
  2270.     int.  If well-defined overflow characteristics are important
  2271.     and/or negative values are not, use the corresponding unsigned
  2272.     types.  (But beware of mixing signed and unsigned in
  2273.     expressions.)  Similar arguments apply when deciding between
  2274.     float and double.
  2275.  
  2276.     Although char or unsigned char can be used as a "tiny" int type,
  2277.     doing so is often more trouble than it's worth, due to
  2278.     unpredictable sign extension and increased code size.
  2279.  
  2280.     These rules obviously don't apply if the address of a variable
  2281.     is taken and must have a particular type.
  2282.  
  2283.     If for some reason you need to declare something with an _exact_
  2284.     size (usually the only good reason for doing so is when
  2285.     attempting to conform to some externally-imposed storage layout,
  2286.     but see question 17.3), be sure to encapsulate the choice behind
  2287.     an appropriate typedef.
  2288.  
  2289. 10.2:    What should the 64-bit type on new, 64-bit machines be?
  2290.  
  2291. A:    Some vendors of C products for 64-bit machines support 64-bit
  2292.     long ints.  Others fear that too much existing code depends on
  2293.     sizeof(int) == sizeof(long) == 32 bits, and introduce a new 64-
  2294.     bit long long (or __longlong) type instead.
  2295.  
  2296.     Programmers interested in writing portable code should therefore
  2297.     insulate their 64-bit type needs behind appropriate typedefs.
  2298.     Vendors who feel compelled to introduce a new, longer integral
  2299.     type should advertise it as being "at least 64 bits" (which is
  2300.     truly new; a type traditional C doesn't have), and not "exactly
  2301.     64 bits."
  2302.  
  2303. 10.3:    I can't seem to define a linked list successfully.  I tried
  2304.  
  2305.         typedef struct
  2306.             {
  2307.             char *item;
  2308.             NODEPTR next;
  2309.             } *NODEPTR;
  2310.  
  2311.     but the compiler gave me error messages.  Can't a struct in C
  2312.     contain a pointer to itself?
  2313.  
  2314. A:    Structs in C can certainly contain pointers to themselves; the
  2315.     discussion and example in section 6.5 of K&R make this clear.
  2316.     The problem with this example is that the NODEPTR typedef is not
  2317.     complete at the point where the "next" field is declared.  To
  2318.     fix it, first give the structure a tag ("struct node").  Then,
  2319.     declare the "next" field as "struct node *next;", and/or move
  2320.     the typedef declaration wholly before or wholly after the struct
  2321.     declaration.  One corrected version would be
  2322.  
  2323.         struct node
  2324.             {
  2325.             char *item;
  2326.             struct node *next;
  2327.             };
  2328.  
  2329.         typedef struct node *NODEPTR;
  2330.  
  2331.     , and there are at least three other equivalently correct ways
  2332.     of arranging it.
  2333.  
  2334.     A similar problem, with a similar solution, can arise when
  2335.     attempting to declare a pair of typedef'ed mutually referential
  2336.     structures.
  2337.  
  2338.     References: K&R I Sec. 6.5 p. 101; K&R II Sec. 6.5 p. 139; H&S
  2339.     Sec. 5.6.1 p. 102; ANSI Sec. 3.5.2.3 .
  2340.  
  2341. 10.4:    How do I declare an array of N pointers to functions returning
  2342.     pointers to functions returning pointers to characters?
  2343.  
  2344. A:    This question can be answered in at least three ways:
  2345.  
  2346.     1.  char *(*(*a[N])())();
  2347.  
  2348.     2.  Build the declaration up in stages, using typedefs:
  2349.  
  2350.         typedef char *pc;    /* pointer to char */
  2351.         typedef pc fpc();    /* function returning pointer to char */
  2352.         typedef fpc *pfpc;    /* pointer to above */
  2353.         typedef pfpc fpfpc();    /* function returning... */
  2354.         typedef fpfpc *pfpfpc;    /* pointer to... */
  2355.         pfpfpc a[N];        /* array of... */
  2356.  
  2357.     3.  Use the cdecl program, which turns English into C and vice
  2358.         versa:
  2359.  
  2360.         cdecl> declare a as array of pointer to function returning
  2361.              pointer to function returning pointer to char
  2362.         char *(*(*a[])())()
  2363.  
  2364.         cdecl can also explain complicated declarations, help with
  2365.         casts, and indicate which set of parentheses the arguments
  2366.         go in (for complicated function definitions, like the
  2367.         above).  Versions of cdecl are in volume 14 of
  2368.         comp.sources.unix (see question 17.12) and K&R II.
  2369.  
  2370.     Any good book on C should explain how to read these complicated
  2371.     C declarations "inside out" to understand them ("declaration
  2372.     mimics use").
  2373.  
  2374.     References: K&R II Sec. 5.12 p. 122; H&S Sec. 5.10.1 p. 116.
  2375.  
  2376. 10.5:    I'm building a state machine with a bunch of functions, one for
  2377.     each state.  I want to implement state transitions by having
  2378.     each function return a pointer to the next state function.  I
  2379.     find a limitation in C's declaration mechanism: there's no way
  2380.     to declare these functions as returning a pointer to a function
  2381.     returning a pointer to a function returning a pointer to a
  2382.     function...
  2383.  
  2384. A:    You can't do it directly.  Either have the function return a
  2385.     generic function pointer type, and apply a cast before calling
  2386.     through it; or have it return a structure containing only a
  2387.     pointer to a function returning that structure.
  2388.  
  2389. 10.6:    My compiler is complaining about an invalid redeclaration of a
  2390.     function, but I only define it once and call it once.
  2391.  
  2392. A:    If the first call precedes the definition, the compiler will
  2393.     assume a function returns an int.  Non-int functions must be
  2394.     declared before they are called.
  2395.  
  2396.     References: K&R I Sec. 4.2 pp. 70; K&R II Sec. 4.2 p. 72; ANSI
  2397.     Sec. 3.3.2.2 .
  2398.  
  2399. 10.7:    What's the best way to declare and define global variables?
  2400.  
  2401. A:    First, though there can be many _declarations_ (and in many
  2402.     translation units) of a single "global" (strictly speaking,
  2403.     "external") variable (or function), there must be exactly one
  2404.     _definition_.  (The definition is the declaration that actually
  2405.     allocates space, and provides an initialization value, if any.)
  2406.     It is best to place the definition in some central (to the
  2407.     program, or to the module) .c file, with an external declaration
  2408.     in a header (".h") file, which is #included wherever the
  2409.     declaration is needed.  The .c file containing the definition
  2410.     should also #include the header file containing the external
  2411.     declaration, so that the compiler can check that the
  2412.     declarations match.
  2413.  
  2414.     This rule promotes a high degree of portability, and is
  2415.     consistent with the requirements of the ANSI C Standard.  Note
  2416.     that Unix compilers and linkers typically use a "common model"
  2417.     which allows multiple (uninitialized) definitions.  A few very
  2418.     odd systems may require an explicit initializer to distinguish a
  2419.     definition from an external declaration.
  2420.  
  2421.     It is possible to use preprocessor tricks to arrange that the
  2422.     declaration need only be typed once, in the header file, and
  2423.     "turned into" a definition, during exactly one #inclusion, via a
  2424.     special #define.
  2425.  
  2426.     References: K&R I Sec. 4.5 pp. 76-7; K&R II Sec. 4.4 pp. 80-1;
  2427.     ANSI Sec. 3.1.2.2 (esp. Rationale), Secs. 3.7, 3.7.2,
  2428.     Sec. F.5.11; H&S Sec. 4.8 pp. 79-80; CT&P Sec. 4.2 pp. 54-56.
  2429.  
  2430. 10.8:    What does extern mean in a function declaration?
  2431.  
  2432. A:    It can be used as a stylistic hint to indicate that the
  2433.     function's definition is probably in another source file, but
  2434.     there is no formal difference between
  2435.  
  2436.         extern int f();
  2437.     and
  2438.         int f();
  2439.  
  2440.     References: ANSI Sec. 3.1.2.2 .
  2441.  
  2442. 10.9:    I finally figured out the syntax for declaring pointers to
  2443.     functions, but now how do I initialize one?
  2444.  
  2445. A:    Use something like
  2446.  
  2447.         extern int func();
  2448.         int (*fp)() = func;
  2449.  
  2450.     When the name of a function appears in an expression but is not
  2451.     being called (i.e. is not followed by a "("), it "decays" into a
  2452.     pointer (i.e. it has its address implicitly taken), much as an
  2453.     array name does.
  2454.  
  2455.     An explicit extern declaration for the function is normally
  2456.     needed, since implicit external function declaration does not
  2457.     happen in this case (again, because the function name is not
  2458.     followed by a "(").
  2459.  
  2460. 10.10:    I've seen different methods used for calling through pointers to
  2461.     functions.  What's the story?
  2462.  
  2463. A:    Originally, a pointer to a function had to be "turned into" a
  2464.     "real" function, with the * operator (and an extra pair of
  2465.     parentheses, to keep the precedence straight), before calling:
  2466.  
  2467.         int r, func(), (*fp)() = func;
  2468.         r = (*fp)();
  2469.  
  2470.     It can also be argued that functions are always called through
  2471.     pointers, but that "real" functions decay implicitly into
  2472.     pointers (in expressions, as they do in initializations) and so
  2473.     cause no trouble.  This reasoning, made widespread through pcc
  2474.     and adopted in the ANSI standard, means that
  2475.  
  2476.         r = fp();
  2477.  
  2478.     is legal and works correctly, whether fp is a function or a
  2479.     pointer to one.  (The usage has always been unambiguous; there
  2480.     is nothing you ever could have done with a function pointer
  2481.     followed by an argument list except call through it.)  An
  2482.     explicit * is harmless, and still allowed (and recommended, if
  2483.     portability to older compilers is important).
  2484.  
  2485.     References: ANSI Sec. 3.3.2.2 p. 41, Rationale p. 41.
  2486.  
  2487. 10.11:    What's the auto keyword good for?
  2488.  
  2489. A:    Nothing; it's obsolete.
  2490.  
  2491.  
  2492. Section 11. Stdio
  2493.  
  2494. 11.1:    Why doesn't this code:
  2495.  
  2496.         char c;
  2497.         while((c = getchar()) != EOF)...
  2498.  
  2499.     work?
  2500.  
  2501. A:    For one thing, the variable to hold getchar's return value must
  2502.     be an int.  getchar can return all possible character values, as
  2503.     well as EOF.  By passing getchar's return value through a char,
  2504.     either a normal character might be misinterpreted as EOF, or the
  2505.     EOF might be altered and so never seen.
  2506.  
  2507.     References: CT&P Sec. 5.1 p. 70.
  2508.  
  2509. 11.2:    Why doesn't the code scanf("%d", i); work?
  2510.  
  2511. A:    scanf needs pointers to the variables it is to fill in; you must
  2512.     call scanf("%d", &i);
  2513.  
  2514. 11.3:    Why doesn't this code:
  2515.  
  2516.         double d;
  2517.         scanf("%f", &d);
  2518.  
  2519.     work?
  2520.  
  2521. A:    scanf uses %lf for values of type double, and %f for float.
  2522.     (Note the discrepancy with printf, which uses %f for both double
  2523.     and float, due to C's default argument promotion rules.)
  2524.  
  2525. 11.4:    Why won't the code
  2526.  
  2527.         while(!feof(infp)) {
  2528.             fgets(buf, MAXLINE, infp);
  2529.             fputs(buf, outfp);
  2530.         }
  2531.  
  2532.     work?
  2533.  
  2534. A:    C's I/O is not like Pascal's.  EOF is only indicated _after_ an
  2535.     input routine has tried to read, and has reached end-of-file.
  2536.     Usually, you should just check the return value of the input
  2537.     routine (fgets in this case); often, you don't need to use
  2538.     feof() at all.
  2539.  
  2540. 11.5:    Why does everyone say not to use gets()?
  2541.  
  2542. A:    It cannot be told the size of the buffer it's to read into, so
  2543.     it cannot be prevented from overflowing that buffer.  See
  2544.     question 3.1 for a code fragment illustrating the replacement of
  2545.     gets() with fgets().
  2546.  
  2547. 11.6:    Why does errno contain ENOTTY after a call to printf?
  2548.  
  2549. A:    Many implementations of the stdio package adjust their behavior
  2550.     slightly if stdout is a terminal.  To make the determination,
  2551.     these implementations perform an operation which fails (with
  2552.     ENOTTY) if stdout is not a terminal.  Although the output
  2553.     operation goes on to complete successfully, errno still contains
  2554.     ENOTTY.
  2555.  
  2556.     References: CT&P Sec. 5.4 p. 73.
  2557.  
  2558. 11.7:    My program's prompts and intermediate output don't always show
  2559.     up on the screen, especially when I pipe the output through
  2560.     another program.
  2561.  
  2562. A:    It is best to use an explicit fflush(stdout) whenever output
  2563.     should definitely be visible.  Several mechanisms attempt to
  2564.     perform the fflush for you, at the "right time," but they tend
  2565.     to apply only when stdout is a terminal.  (See question 11.6.)
  2566.  
  2567. 11.8:    When I read from the keyboard with scanf, it seems to hang until
  2568.     I type one extra line of input.
  2569.  
  2570. A:    scanf was designed for free-format input, which is seldom what
  2571.     you want when reading from the keyboard.  In particular, "\n" in
  2572.     a format string does _not_ mean to expect a newline, but rather
  2573.     to read and discard characters as long as each is a whitespace
  2574.     character.
  2575.  
  2576.     A related problem is that unexpected non-numeric input can cause
  2577.     scanf to "jam."  Because of these problems, it is usually better
  2578.     to use fgets to read a whole line, and then use sscanf or other
  2579.     string functions to pick apart the line buffer.  If you do use
  2580.     sscanf, don't forget to check the return value to make sure that
  2581.     the expected number of items were found.
  2582.  
  2583. 11.9:    I'm trying to update a file in place, by using fopen mode "r+",
  2584.     then reading a certain string, and finally writing back a
  2585.     modified string, but it's not working.
  2586.  
  2587. A:    Be sure to call fseek before you write, both to seek back to the
  2588.     beginning of the string you're trying to overwrite, and because
  2589.     an fseek or fflush is always required between reading and
  2590.     writing in the read/write "+" modes.
  2591.  
  2592.     References: ANSI Sec. 4.9.5.3 p. 131.
  2593.  
  2594. 11.10:    How can I read one character at a time, without waiting for the
  2595.     RETURN key?
  2596.  
  2597. A:    See question 16.1.
  2598.  
  2599. 11.11:    How can I flush pending input so that a user's typeahead isn't
  2600.     read at the next prompt?  Will fflush(stdin) work?
  2601.  
  2602. A:    fflush is defined only for output streams.  Since its definition
  2603.     of "flush" is to complete the writing of buffered characters
  2604.     (not to discard them), discarding unread input would not be an
  2605.     analogous meaning for fflush on input streams.  There is no
  2606.     standard way to discard unread characters from a stdio input
  2607.     buffer, nor would such a way be sufficient; unread characters
  2608.     can also accumulate in other, OS-level input buffers.
  2609.  
  2610. 11.12:    How can I redirect stdin or stdout to a file from within a
  2611.     program?
  2612.  
  2613. A:    Use freopen.
  2614.  
  2615. 11.13:    Once I've used freopen, how can I get the original stdout (or
  2616.     stdin) back?
  2617.  
  2618. A:    If you need to switch back and forth, the best all-around
  2619.     solution is not to use freopen in the first place.  Try using
  2620.     your own explicit output (or input) stream variable, which you
  2621.     can reassign at will, while leaving the original stdout (or
  2622.     stdin) undisturbed.
  2623.  
  2624. 11.14:    How can I recover the file name given an open file descriptor?
  2625.  
  2626. A:    This problem is, in general, insoluble.  Under Unix, for
  2627.     instance, a scan of the entire disk, (perhaps requiring special
  2628.     permissions) would theoretically be required, and would fail if
  2629.     the file descriptor was a pipe or referred to a deleted file
  2630.     (and could give a misleading answer for a file with multiple
  2631.     links).  It is best to remember the names of files yourself when
  2632.     you open them (perhaps with a wrapper function around fopen).
  2633.  
  2634.  
  2635. Section 12. Library Subroutines
  2636.  
  2637. 12.1:    Why does strncpy not always place a '\0' termination in the
  2638.     destination string?
  2639.  
  2640. A:    strncpy was first designed to handle a now-obsolete data
  2641.     structure, the fixed-length, not-necessarily-\0-terminated
  2642.     "string."  strncpy is admittedly a bit cumbersome to use in
  2643.     other contexts, since you must often append a '\0' to the
  2644.     destination string by hand.
  2645.  
  2646. 12.2:    I'm trying to sort an array of strings with qsort, using strcmp
  2647.     as the comparison function, but it's not working.
  2648.  
  2649. A:    By "array of strings" you probably mean "array of pointers to
  2650.     char."  The arguments to qsort's comparison function are
  2651.     pointers to the objects being sorted, in this case, pointers to
  2652.     pointers to char.  (strcmp, of course, accepts simple pointers
  2653.     to char.)
  2654.  
  2655.     The comparison routine's arguments are expressed as "generic
  2656.     pointers," const void * or char *.  They must be converted back
  2657.     to what they "really are" (char **) and dereferenced, yielding
  2658.     char *'s which can be usefully compared.  Write a comparison
  2659.     function like this:
  2660.  
  2661.         int pstrcmp(p1, p2)    /* compare strings through pointers */
  2662.         char *p1, *p2;        /* const void * for ANSI C */
  2663.         {
  2664.             return strcmp(*(char **)p1, *(char **)p2);
  2665.         }
  2666.  
  2667.     Beware of the discussion in K&R II Sec. 5.11 pp. 119-20, which
  2668.     is not discussing Standard library qsort.
  2669.  
  2670. 12.3:    Now I'm trying to sort an array of structures with qsort.  My
  2671.     comparison routine takes pointers to structures, but the
  2672.     compiler complains that the function is of the wrong type for
  2673.     qsort.  How can I cast the function pointer to shut off the
  2674.     warning?
  2675.  
  2676. A:    The conversions must be in the comparison function, which must
  2677.     be declared as accepting "generic pointers" (const void * or
  2678.     char *) as discussed in question 12.2 above.  The code might
  2679.     look like
  2680.  
  2681.         int mystructcmp(p1, p2)
  2682.         char *p1, *p2;        /* const void * for ANSI C */
  2683.         {
  2684.             struct mystruct *sp1 = (struct mystruct *)p1;
  2685.             struct mystruct *sp2 = (struct mystruct *)p2;
  2686.             /* now compare sp1->whatever and *sp2-> ... */
  2687.         }
  2688.  
  2689.     (If, on the other hand, you're sorting pointers to structures,
  2690.     you'll need indirection, as in question 12.2:
  2691.     sp1 = *(struct mystruct **)p1 .)
  2692.  
  2693. 12.4:    How can I convert numbers to strings (the opposite of atoi)?  Is
  2694.     there an itoa function?
  2695.  
  2696. A:    Just use sprintf.  (You'll have to allocate space for the result
  2697.     somewhere anyway; see questions 3.1 and 3.2.  Don't worry that
  2698.     sprintf may be overkill, potentially wasting run time or code
  2699.     space; it works well in practice.)
  2700.  
  2701.     References: K&R I Sec. 3.6 p. 60; K&R II Sec. 3.6 p. 64.
  2702.  
  2703. 12.5:    How can I get the current date or time of day in a C program?
  2704.  
  2705. A:    Just use the time, ctime, and/or localtime functions.  (These
  2706.     routines have been around for years, and are in the ANSI
  2707.     standard.)  Here is a simple example:
  2708.  
  2709.         #include <stdio.h>
  2710.         #include <time.h>
  2711.  
  2712.         main()
  2713.         {
  2714.             time_t now = time((time_t *)NULL);
  2715.             printf("It's %.24s.\n", ctime(&now));
  2716.             return 0;
  2717.         }
  2718.  
  2719.     References: ANSI Sec. 4.12 .
  2720.  
  2721. 12.6:    I know that the library routine localtime will convert a time_t
  2722.     into a broken-down struct tm, and that ctime will convert a
  2723.     time_t to a printable string.  How can I perform the inverse
  2724.     operations of converting a struct tm or a string into a time_t?
  2725.  
  2726. A:    ANSI C specifies a library routine, mktime, which converts a
  2727.     struct tm to a time_t.  Several public-domain versions of this
  2728.     routine are available in case your compiler does not support it
  2729.     yet.
  2730.  
  2731.     Converting a string to a time_t is harder, because of the wide
  2732.     variety of date and time formats which should be parsed.  Some
  2733.     systems provide a strptime function; another popular routine is
  2734.     partime (widely distributed with the RCS package), but these are
  2735.     less likely to become standardized.
  2736.  
  2737.     References: K&R II Sec. B10 p. 256; H&S Sec. 20.4 p. 361; ANSI
  2738.     Sec. 4.12.2.3 .
  2739.  
  2740. 12.7:    How can I add n days to a date?  How can I find the difference
  2741.     between two dates?
  2742.  
  2743. A:    The ANSI/ISO Standard C mktime and difftime functions provide
  2744.     support for both problems.  mktime accepts non-normalized dates,
  2745.     so it is straightforward to take a filled in struct tm, add or
  2746.     subtract from the tm_mday field, and call mktime to normalize
  2747.     the year, month, and day fields (and convert to a time_t value).
  2748.     difftime computes the difference, in seconds, between two time_t
  2749.     values; mktime can be used to compute time_t values for two
  2750.     dates to be subtracted.  (Note, however, that these solutions
  2751.     only work for dates which can be represented as time_t's.)  See
  2752.     also questions 12.6 and 17.28.
  2753.  
  2754.     References: K&R II Sec. B10 p. 256; H&S Secs. 20.4, 20.5
  2755.     pp. 361-362; ANSI Secs. 4.12.2.2, 4.12.2.3 .
  2756.  
  2757. 12.8:    I need a random number generator.
  2758.  
  2759. A:    The standard C library has one: rand().  The implementation on
  2760.     your system may not be perfect, but writing a better one isn't
  2761.     necessarily easy, either.
  2762.  
  2763.     References: ANSI Sec. 4.10.2.1 p. 154; Knuth Vol. 2 Chap. 3
  2764.     pp. 1-177.
  2765.  
  2766. 12.9:    How can I get random integers in a certain range?
  2767.  
  2768. A:    The obvious way,
  2769.  
  2770.         rand() % N
  2771.  
  2772.     (where N is of course the range) is poor, because the low-order
  2773.     bits of many random number generators are distressingly non-
  2774.     random.  (See question 12.11.)  A better method is something
  2775.     like
  2776.  
  2777.         (int)((double)rand() / ((double)RAND_MAX + 1) * N)
  2778.  
  2779.     If you're worried about using floating point, you could try
  2780.  
  2781.         rand() / (RAND_MAX / N + 1)
  2782.  
  2783.     Both methods obviously require knowing RAND_MAX (which ANSI
  2784.     defines in <stdlib.h>), and assume that N is much less than
  2785.     RAND_MAX.
  2786.  
  2787. 12.10:    Each time I run my program, I get the same sequence of numbers
  2788.     back from rand().
  2789.  
  2790. A:    You can call srand() to seed the pseudo-random number generator
  2791.     with a more random initial value.  Popular seed values are the
  2792.     time of day, or the elapsed time before the user presses a key
  2793.     (although keypress times are hard to determine portably; see
  2794.     question 16.10).
  2795.  
  2796.     References: ANSI Sec. 4.10.2.2 p. 154.
  2797.  
  2798. 12.11:    I need a random true/false value, so I'm taking rand() % 2, but
  2799.     it's just alternating 0, 1, 0, 1, 0...
  2800.  
  2801. A:    Poor pseudorandom number generators (such as the ones
  2802.     unfortunately supplied with some systems) are not very random in
  2803.     the low-order bits.  Try using the higher-order bits.  See
  2804.     question 12.9.
  2805.  
  2806. 12.12:    I'm trying to port this        A:  These routines are variously
  2807.     old program.  Why do I            obsolete; you should
  2808.     get "undefined external"        instead:
  2809.     errors for:
  2810.  
  2811.     index?                    use strchr.
  2812.     rindex?                    use strrchr.
  2813.     bcopy?                    use memmove, after
  2814.                         interchanging the first and
  2815.                         second arguments (see also
  2816.                         question 5.15).
  2817.     bcmp?                    use memcmp.
  2818.     bzero?                    use memset, with a second
  2819.                         argument of 0.
  2820.  
  2821. 12.13:    I keep getting errors due to library routines being undefined,
  2822.     but I'm #including all the right header files.
  2823.  
  2824. A:    In some cases (especially if the routines are nonstandard) you
  2825.     may have to explicitly ask for the correct libraries to be
  2826.     searched when you link the program.  See also question 15.2.
  2827.  
  2828. 12.14:    I'm still getting errors due to library routines being
  2829.     undefined, even though I'm using -l to request the libraries
  2830.     while linking.
  2831.  
  2832. A:    Many linkers make one pass over the list of object files and
  2833.     libraries you specify, and extract from libraries only those
  2834.     modules which satisfy references which have so far come up as
  2835.     undefined.  Therefore, the order in which libraries are listed
  2836.     with respect to object files (and each other) is significant;
  2837.     usually, you want to search the libraries last (i.e., under
  2838.     Unix, put any -l switches towards the end of the command line).
  2839.  
  2840. 12.15:    I need some code to do regular expression matching.
  2841.  
  2842. A:    Look for the regexp library (supplied with many Unix systems),
  2843.     or get Henry Spencer's regexp package from cs.toronto.edu in
  2844.     pub/regexp.shar.Z (see also question 17.12).
  2845.  
  2846. 12.16:    How can I split up a command line into argc and argv, like the
  2847.     shell does?
  2848.  
  2849. A:    Most systems have a routine called strtok.
  2850.  
  2851.     References: ANSI Sec. 4.11.5.8; K&R II Sec. B3 p. 250; H&S
  2852.     Sec. 15.7; PCS p. 178.
  2853.  
  2854.  
  2855. Section 13. Lint
  2856.  
  2857. 13.1:    I just typed in this program, and it's acting strangely.  Can
  2858.     you see anything wrong with it?
  2859.  
  2860. A:    Try running lint first (perhaps with the -a, -c, -h, -p and/or
  2861.     other options).  Many C compilers are really only half-
  2862.     compilers, electing not to diagnose numerous source code
  2863.     difficulties which would not actively preclude code generation.
  2864.  
  2865. 13.2:    How can I shut off the "warning: possible pointer alignment
  2866.     problem" message lint gives me for each call to malloc?
  2867.  
  2868. A:    The problem is that traditional versions of lint do not know,
  2869.     and cannot be told, that malloc "returns a pointer to space
  2870.     suitably aligned for storage of any type of object."  It is
  2871.     possible to provide a pseudoimplementation of malloc, using a
  2872.     #define inside of #ifdef lint, which effectively shuts this
  2873.     warning off, but a simpleminded #definition will also suppress
  2874.     meaningful messages about truly incorrect invocations.  It may
  2875.     be easier simply to ignore the message, perhaps in an automated
  2876.     way with grep -v.
  2877.  
  2878. 13.3:    Where can I get an ANSI-compatible lint?
  2879.  
  2880. A:    A product called FlexeLint is available (in "shrouded source
  2881.     form," for compilation on 'most any system) from
  2882.  
  2883.         Gimpel Software
  2884.         3207 Hogarth Lane
  2885.         Collegeville, PA  19426  USA
  2886.         (+1) 215 584 4261
  2887.  
  2888.     The System V release 4 lint is ANSI-compatible, and is available
  2889.     separately (bundled with other C tools) from UNIX Support Labs
  2890.     (a subsidiary of AT&T), or from System V resellers.
  2891.  
  2892.  
  2893. Section 14. Style
  2894.  
  2895. 14.1:    Here's a neat trick:
  2896.  
  2897.         if(!strcmp(s1, s2))
  2898.  
  2899.     Is this good style?
  2900.  
  2901. A:    It is not particularly good style, although it is a popular
  2902.     idiom.  The test succeeds if the two strings are equal, but its
  2903.     form suggests that it tests for inequality.
  2904.  
  2905.     Another solution is to use a macro:
  2906.  
  2907.         #define Streq(s1, s2) (strcmp((s1), (s2)) == 0)
  2908.  
  2909.     Opinions on code style, like those on religion, can be debated
  2910.     endlessly.  Though good style is a worthy goal, and can usually
  2911.     be recognized, it cannot be codified.
  2912.  
  2913. 14.2:    What's the best style for code layout in C?
  2914.  
  2915. A:    K&R, while providing the example most often copied, also supply
  2916.     a good excuse for avoiding it:
  2917.  
  2918.         The position of braces is less important,
  2919.         although people hold passionate beliefs.  We
  2920.         have chosen one of several popular styles.  Pick
  2921.         a style that suits you, then use it
  2922.         consistently.
  2923.  
  2924.     It is more important that the layout chosen be consistent (with
  2925.     itself, and with nearby or common code) than that it be
  2926.     "perfect."  If your coding environment (i.e. local custom or
  2927.     company policy) does not suggest a style, and you don't feel
  2928.     like inventing your own, just copy K&R.  (The tradeoffs between
  2929.     various indenting and brace placement options can be
  2930.     exhaustively and minutely examined, but don't warrant repetition
  2931.     here.  See also the Indian Hill Style Guide.)
  2932.  
  2933.     The elusive quality of "good style" involves much more than mere
  2934.     code layout details; don't spend time on formatting to the
  2935.     exclusion of more substantive code quality issues.
  2936.  
  2937.     References: K&R Sec. 1.2 p. 10.
  2938.  
  2939. 14.3:    Where can I get the "Indian Hill Style Guide" and other coding
  2940.     standards?
  2941.  
  2942. A:    Various documents are available for anonymous ftp from:
  2943.  
  2944.         Site:            File or directory:
  2945.  
  2946.         cs.washington.edu    ~ftp/pub/cstyle.tar.Z
  2947.         (128.95.1.4)        (the updated Indian Hill guide)
  2948.  
  2949.         cs.toronto.edu        doc/programming
  2950.  
  2951.         giza.cis.ohio-state.edu    pub/style-guide
  2952.  
  2953.  
  2954. Section 15. Floating Point
  2955.  
  2956. 15.1:    My floating-point calculations are acting strangely and giving
  2957.     me different answers on different machines.
  2958.  
  2959. A:    First, make sure that you have #included <math.h>, and correctly
  2960.     declared other functions returning double.
  2961.  
  2962.     If the problem isn't that simple, recall that most digital
  2963.     computers use floating-point formats which provide a close but
  2964.     by no means exact simulation of real number arithmetic.
  2965.     Underflow, cumulative precision loss, and other anomalies are
  2966.     often troublesome.
  2967.  
  2968.     Don't assume that floating-point results will be exact, and
  2969.     especially don't assume that floating-point values can be
  2970.     compared for equality.  (Don't throw haphazard "fuzz factors"
  2971.     in, either.)
  2972.  
  2973.     These problems are no worse for C than they are for any other
  2974.     computer language.  Floating-point semantics are usually defined
  2975.     as "however the processor does them;" otherwise a compiler for a
  2976.     machine without the "right" model would have to do prohibitively
  2977.     expensive emulations.
  2978.  
  2979.     This article cannot begin to list the pitfalls associated with,
  2980.     and workarounds appropriate for, floating-point work.  A good
  2981.     programming text should cover the basics.
  2982.  
  2983.     References: EoPS Sec. 6 pp. 115-8.
  2984.  
  2985. 15.2:    I'm trying to do some simple trig, and I am #including <math.h>,
  2986.     but I keep getting "undefined: _sin" compilation errors.
  2987.  
  2988. A:    Make sure you're linking with the correct math library.  For
  2989.     instance, under Unix, you usually need to use the -lm option,
  2990.     and at the _end_ of the command line, when compiling/linking.
  2991.     See also question 12.14.
  2992.  
  2993. 15.3:    Why doesn't C have an exponentiation operator?
  2994.  
  2995. A:    Because few processors have an exponentiation instruction.
  2996.     Instead, you can #include <math.h> and use the pow() function,
  2997.     although explicit multiplication is often better for small
  2998.     positive integral exponents.
  2999.  
  3000.     References: ANSI Sec. 4.5.5.1 .
  3001.  
  3002. 15.4:    How do I round numbers?
  3003.  
  3004. A:    The simplest and most straightforward way is with code like
  3005.  
  3006.         (int)(x + 0.5)
  3007.  
  3008.     This won't work properly for negative numbers, though.
  3009.  
  3010. 15.5:    How do I test for IEEE NaN and other special values?
  3011.  
  3012. A:    Many systems with high-quality IEEE floating-point
  3013.     implementations provide facilities (e.g. an isnan() macro) to
  3014.     deal with these values cleanly, and the Numerical C Extensions
  3015.     Group (NCEG) is working to formally standardize such facilities.
  3016.     A crude but usually effective test for NaN is exemplified by
  3017.  
  3018.         #define isnan(x) ((x) != (x))
  3019.  
  3020.     although non-IEEE-aware compilers may optimize the test away.
  3021.  
  3022. 15.6:    I'm having trouble with a Turbo C program which crashes and says
  3023.     something like "floating point formats not linked."
  3024.  
  3025. A:    Some compilers for small machines, including Turbo C (and
  3026.     Ritchie's original PDP-11 compiler), leave out floating point
  3027.     support if it looks like it will not be needed.  In particular,
  3028.     the non-floating-point versions of printf and scanf save space
  3029.     by not including code to handle %e, %f, and %g.  It happens that
  3030.     Turbo C's heuristics for determining whether the program uses
  3031.     floating point are insufficient, and the programmer must
  3032.     sometimes insert an extra, explicit call to a floating-point
  3033.     library routine to force loading of floating-point support.
  3034.  
  3035.  
  3036. Section 16. System Dependencies
  3037.  
  3038. 16.1:    How can I read a single character from the keyboard without
  3039.     waiting for a newline?
  3040.  
  3041. A:    Contrary to popular belief and many people's wishes, this is not
  3042.     a C-related question.  (Nor are closely-related questions
  3043.     concerning the echo of keyboard input.)  The delivery of
  3044.     characters from a "keyboard" to a C program is a function of the
  3045.     operating system in use, and has not been standardized by the C
  3046.     language.  Some versions of curses have a cbreak() function
  3047.     which does what you want.  If you're specifically trying to read
  3048.     a short password without echo, you might try getpass().  Under
  3049.     Unix, use ioctl to play with the terminal driver modes (CBREAK
  3050.     or RAW under "classic" versions; ICANON, c_cc[VMIN] and
  3051.     c_cc[VTIME] under System V or Posix systems).  Under MS-DOS, use
  3052.     getch().  Under VMS, try the Screen Management (SMG$) routines,
  3053.     or curses, or issue low-level $QIO's with the IO$_READVBLK (and
  3054.     perhaps IO$M_NOECHO) function codes to ask for one character at
  3055.     a time.  Under other operating systems, you're on your own.
  3056.     Beware that some operating systems make this sort of thing
  3057.     impossible, because character collection into input lines is
  3058.     done by peripheral processors not under direct control of the
  3059.     CPU running your program.
  3060.  
  3061.     Operating system specific questions are not appropriate for
  3062.     comp.lang.c .  Many common questions are answered in
  3063.     frequently-asked questions postings in such groups as
  3064.     comp.unix.questions and comp.os.msdos.programmer .  Note that
  3065.     the answers are often not unique even across different variants
  3066.     of a system; bear in mind when answering system-specific
  3067.     questions that the answer that applies to your system may not
  3068.     apply to everyone else's.
  3069.  
  3070.     References: PCS Sec. 10 pp. 128-9, Sec. 10.1 pp. 130-1.
  3071.  
  3072. 16.2:    How can I find out if there are characters available for reading
  3073.     (and if so, how many)?  Alternatively, how can I do a read that
  3074.     will not block if there are no characters available?
  3075.  
  3076. A:    These, too, are entirely operating-system-specific.  Some
  3077.     versions of curses have a nodelay() function.  Depending on your
  3078.     system, you may also be able to use "nonblocking I/O", or a
  3079.     system call named "select", or the FIONREAD ioctl, or kbhit(),
  3080.     or rdchk(), or the O_NDELAY option to open() or fcntl().
  3081.  
  3082. 16.3:    How can I clear the screen?  How can I print things in inverse
  3083.     video?
  3084.  
  3085. A:    Such things depend on the terminal type (or display) you're
  3086.     using.  You will have to use a library such as termcap or
  3087.     curses, or some system-specific routines, to perform these
  3088.     functions.
  3089.  
  3090. 16.4:    How do I read the mouse?
  3091.  
  3092. A:    Consult your system documentation, or ask on an appropriate
  3093.     system-specific newsgroup (but check its FAQ list first).  Mouse
  3094.     handling is completely different under the X window system, MS-
  3095.     DOS, Macintosh, and probably every other system.
  3096.  
  3097. 16.5:    How can my program discover the complete pathname to the
  3098.     executable file from which it was invoked?
  3099.  
  3100. A:    argv[0] may contain all or part of the pathname, or it may
  3101.     contain nothing.  You may be able to duplicate the command
  3102.     language interpreter's search path logic to locate the
  3103.     executable if the name in argv[0] is present but incomplete.
  3104.     However, there is no guaranteed or portable solution.
  3105.  
  3106. 16.6:    How can a process change an environment variable in its caller?
  3107.  
  3108. A:    In general, it cannot.  Different operating systems implement
  3109.     name/value functionality similar to the Unix environment in
  3110.     different ways.  Whether the "environment" can be usefully
  3111.     altered by a running program, and if so, how, is system-
  3112.     dependent.
  3113.  
  3114.     Under Unix, a process can modify its own environment (some
  3115.     systems provide setenv() and/or putenv() functions to do this),
  3116.     and the modified environment is usually passed on to any child
  3117.     processes, but it is _not_ propagated back to the parent
  3118.     process.
  3119.  
  3120. 16.7:    How can I check whether a file exists?  I want to query the user
  3121.     if a requested output file already exists.
  3122.  
  3123. A:    You can try the access() routine, although it's got a few
  3124.     problems.  (It isn't atomic with respect to the following
  3125.     action, and it has anomalies if the program calling it is
  3126.     running as root.)
  3127.  
  3128. 16.8:    How can I find out the size of a file, prior to reading it in?
  3129.  
  3130. A:    If the "size of a file" is the number of characters you'll be
  3131.     able to read from it in C, it is in general impossible to
  3132.     determine this number in advance.  Under Unix, the stat call
  3133.     will give you an exact answer, and several other systems supply
  3134.     a Unix-like stat which will give an approximate answer.  You can
  3135.     fseek to the end and then use ftell, but this usage is
  3136.     nonportable (it gives you an accurate answer only under Unix,
  3137.     and otherwise a quasi-accurate answer only for ANSI C "binary"
  3138.     files).  Some systems provide routines called filesize or
  3139.     filelength.
  3140.  
  3141.     Are you sure you have to determine the file's size in advance?
  3142.     Since the most accurate way of determining the size of a file as
  3143.     a C program will see it is to open the file and read it, perhaps
  3144.     you can rearrange the code to learn the size as it reads.
  3145.  
  3146. 16.9:    How can a file be shortened in-place without completely clearing
  3147.     or rewriting it?
  3148.  
  3149. A:    BSD systems provide ftruncate(), several others supply chsize(),
  3150.     and a few may provide a (possibly undocumented) fcntl option
  3151.     F_FREESP.  Under MS-DOS, you can sometimes use write(fd, "", 0).
  3152.     However, there is no truly portable solution.
  3153.  
  3154. 16.10:    How can I implement a delay, or time a user's response, with
  3155.     sub-second resolution?
  3156.  
  3157. A:    Unfortunately, there is no portable way.  V7 Unix, and derived
  3158.     systems, provided a fairly useful ftime() routine with
  3159.     resolution up to a millisecond, but it has disappeared from
  3160.     System V and Posix.  Other routines you might look for on your
  3161.     system include nap(), setitimer(), msleep(), usleep(), clock(),
  3162.     and gettimeofday().  The select() and poll() calls (if
  3163.     available) can be pressed into service to implement simple
  3164.     delays.  On MS-DOS machines, it is possible to reprogram the
  3165.     system timer and timer interrupts.
  3166.  
  3167. 16.11:    How can I read in an object file and jump to routines in it?
  3168.  
  3169. A:    You want a dynamic linker and/or loader.  It is possible to
  3170.     malloc some space and read in object files, but you have to know
  3171.     an awful lot about object file formats, relocation, etc.  Under
  3172.     BSD Unix, you could use system() and ld -A to do the linking for
  3173.     you.  Many (most?) versions of SunOS and System V have the -ldl
  3174.     library which allows object files to be dynamically loaded.
  3175.     There is also a GNU package called "dld".  See also question
  3176.     7.6.
  3177.  
  3178. 16.12:    How can I invoke an operating system command from within a
  3179.     program?
  3180.  
  3181. A:    Use system().
  3182.  
  3183.     References: K&R II Sec. B6 p. 253; ANSI Sec. 4.10.4.5; H&S
  3184.     Sec. 21.2; PCS Sec. 11 p. 179;
  3185.  
  3186. 16.13:    How can I invoke an operating system command and trap its
  3187.     output?
  3188.  
  3189. A:    Unix and some other systems provide a popen() routine, which
  3190.     sets up a stdio stream on a pipe connected to the process
  3191.     running a command, so that the output can be read (or the input
  3192.     supplied).
  3193.  
  3194.     References: PCS Sec. 11 p. 169 .
  3195.  
  3196. 16.14:    How can I read a directory in a C program?
  3197.  
  3198. A:    See if you can use the opendir() and readdir() routines, which
  3199.     are available on most Unix systems.  Implementations also exist
  3200.     for MS-DOS, VMS, and other systems.  (MS-DOS also has FINDFIRST
  3201.     and FINDNEXT routines which do essentially the same thing.)
  3202.  
  3203. 16.15:    How can I do serial ("comm") port I/O?
  3204.  
  3205. A:    It's system-dependent.  Under Unix, you typically open, read,
  3206.     and write a device in /dev, and use the facilities of the
  3207.     terminal driver to adjust its characteristics.  Under MS-DOS,
  3208.     you can either use some primitive BIOS interrupts, or (if you
  3209.     require decent performance) one of any number of interrupt-
  3210.     driven serial I/O packages.
  3211.  
  3212.  
  3213. Section 17. Miscellaneous
  3214.  
  3215. 17.1:    What can I safely assume about the initial values of variables
  3216.     which are not explicitly initialized?  If global variables start
  3217.     out as "zero," is that good enough for null pointers and
  3218.     floating-point zeroes?
  3219.  
  3220. A:    Variables with "static" duration (that is, those declared
  3221.     outside of functions, and those declared with the storage class
  3222.     static), are guaranteed initialized (just once, at program
  3223.     startup) to zero, as if the programmer had typed "= 0".
  3224.     Therefore, such variables are initialized to the null pointer
  3225.     (of the correct type; see also Section 1) if they are pointers,
  3226.     and to 0.0 if they are floating-point.
  3227.  
  3228.     Variables with "automatic" duration (i.e. local variables
  3229.     without the static storage class) start out containing garbage,
  3230.     unless they are explicitly initialized.  Nothing useful can be
  3231.     predicted about the garbage.
  3232.  
  3233.     Dynamically-allocated memory obtained with malloc and realloc is
  3234.     also likely to contain garbage, and must be initialized by the
  3235.     calling program, as appropriate.  Memory obtained with calloc
  3236.     contains all-bits-0, but this is not necessarily useful for
  3237.     pointer or floating-point values (see question 3.13, and section
  3238.     1).
  3239.  
  3240. 17.2:    This code, straight out of a book, isn't compiling:
  3241.  
  3242.         f()
  3243.         {
  3244.         char a[] = "Hello, world!";
  3245.         }
  3246.  
  3247. A:    Perhaps you have a pre-ANSI compiler, which doesn't allow
  3248.     initialization of "automatic aggregates" (i.e. non-static local
  3249.     arrays and structures).  As a workaround, you can make the array
  3250.     global or static.  (You can always initialize local char *
  3251.     variables with string literals, but see question 17.20).  See
  3252.     also questions 5.16 and 5.17.
  3253.  
  3254. 17.3:    How can I write data files which can be read on other machines
  3255.     with different word size, byte order, or floating point formats?
  3256.  
  3257. A:    The best solution is to use text files (usually ASCII), written
  3258.     with fprintf and read with fscanf or the like.  (Similar advice
  3259.     also applies to network protocols.)  Be skeptical of arguments
  3260.     which imply that text files are too big, or that reading and
  3261.     writing them is too slow.  Not only is their efficiency
  3262.     frequently acceptable in practice, but the advantages of being
  3263.     able to manipulate them with standard tools can be overwhelming.
  3264.  
  3265.     If you must use a binary format, you can improve portability,
  3266.     and perhaps take advantage of prewritten I/O libraries, by
  3267.     making use of standardized formats such as Sun's XDR (RFC 1014),
  3268.     OSI's ASN.1, CCITT's X.409, or ISO 8825 "Basic Encoding Rules."
  3269.     See also question 9.11.
  3270.  
  3271. 17.4:    How can I delete a line (or record) from the middle of a file?
  3272.  
  3273. A:    Short of rewriting the file, you probably can't.  See also
  3274.     question 16.9.
  3275.  
  3276. 17.5:    How can I return several values from a function?
  3277.  
  3278. A:    Either pass pointers to locations which the function can fill
  3279.     in, or have the function return a structure containing the
  3280.     desired values, or (in a pinch) consider global variables.  See
  3281.     also questions 2.17, 3.4, and 9.2.
  3282.  
  3283. 17.6:    If I have a char * variable pointing to the name of a function
  3284.     as a string, how can I call that function?
  3285.  
  3286. A:    The most straightforward thing to do is maintain a
  3287.     correspondence table of names and function pointers:
  3288.  
  3289.         int function1(), function2();
  3290.  
  3291.         struct {char *name; int (*funcptr)(); } symtab[] =
  3292.             {
  3293.             "function1",    function1,
  3294.             "function2",    function2,
  3295.             };
  3296.  
  3297.     Then, just search the table for the name, and call through the
  3298.     associated function pointer.  See also questions 9.9 and 16.11.
  3299.  
  3300. 17.7:    I seem to be missing the system header file <sgtty.h>.  Can
  3301.     someone send me a copy?
  3302.  
  3303. A:    Standard headers exist in part so that definitions appropriate
  3304.     to your compiler, operating system, and processor can be
  3305.     supplied.  You cannot just pick up a copy of someone else's
  3306.     header file and expect it to work, unless that person is using
  3307.     exactly the same environment.  Ask your compiler vendor why the
  3308.     file was not provided (or to send a replacement copy).
  3309.  
  3310. 17.8:    How can I call FORTRAN (C++, BASIC, Pascal, Ada, LISP) functions
  3311.     from C?  (And vice versa?)
  3312.  
  3313. A:    The answer is entirely dependent on the machine and the specific
  3314.     calling sequences of the various compilers in use, and may not
  3315.     be possible at all.  Read your compiler documentation very
  3316.     carefully; sometimes there is a "mixed-language programming
  3317.     guide," although the techniques for passing arguments and
  3318.     ensuring correct run-time startup are often arcane.  More
  3319.     information may be found in FORT.gz by Glenn Geers, available
  3320.     via anonymous ftp from suphys.physics.su.oz.au in the src
  3321.     directory.
  3322.  
  3323.     cfortran.h, a C header file, simplifies C/FORTRAN interfacing on
  3324.     many popular machines.  It is available via anonymous ftp from
  3325.     zebra.desy.de (131.169.2.244).
  3326.  
  3327.     In C++, a "C" modifier in an external function declaration
  3328.     indicates that the function is to be called using C calling
  3329.     conventions.
  3330.  
  3331. 17.9:    Does anyone know of a program for converting Pascal or FORTRAN
  3332.     (or LISP, Ada, awk, "Old" C, ...) to C?
  3333.  
  3334. A:    Several public-domain programs are available:
  3335.  
  3336.     p2c    A Pascal to C converter written by Dave Gillespie,
  3337.         posted to comp.sources.unix in March, 1990 (Volume 21);
  3338.         also available by anonymous ftp from
  3339.         csvax.cs.caltech.edu, file pub/p2c-1.20.tar.Z .
  3340.  
  3341.     ptoc    Another Pascal to C converter, this one written in
  3342.         Pascal (comp.sources.unix, Volume 10, also patches in
  3343.         Volume 13?).
  3344.  
  3345.     f2c    A Fortran to C converter jointly developed by people
  3346.         from Bell Labs, Bellcore, and Carnegie Mellon.  To find
  3347.         about f2c, send the mail message "send index from f2c"
  3348.         to netlib@research.att.com or research!netlib.  (It is
  3349.         also available via anonymous ftp on research.att.com, in
  3350.         directory dist/f2c.)
  3351.  
  3352.     This FAQ list's maintainer also has available a list of other
  3353.     commercial translation products, and some for more obscure
  3354.     languages.
  3355.  
  3356.     See also question 5.3.
  3357.  
  3358. 17.10:    Is C++ a superset of C?  Can I use a C++ compiler to compile C
  3359.     code?
  3360.  
  3361. A:    C++ was derived from C, and is largely based on it, but there
  3362.     are some legal C constructs which are not legal C++.  (Many C
  3363.     programs will nevertheless compile correctly in a C++
  3364.     environment.)
  3365.  
  3366. 17.11:    I need:                A:  Look for programs (see also
  3367.                         question 17.12) named:
  3368.  
  3369.     a C cross-reference            cflow, calls, cscope
  3370.     generator
  3371.  
  3372.     a C beautifier/pretty-            cb, indent
  3373.     printer
  3374.  
  3375. 17.12:    Where can I get copies of all these public-domain programs?
  3376.  
  3377. A:    If you have access to Usenet, see the regular postings in the
  3378.     comp.sources.unix and comp.sources.misc newsgroups, which
  3379.     describe, in some detail, the archiving policies and how to
  3380.     retrieve copies.  The usual approach is to use anonymous ftp
  3381.     and/or uucp from a central, public-spirited site, such as uunet
  3382.     (ftp.uu.net, 192.48.96.9).  However, this article cannot track
  3383.     or list all of the available archive sites and how to access
  3384.     them.
  3385.  
  3386.     Ajay Shah maintains an index of free numerical software; it is
  3387.     posted periodically, and available where this FAQ list is
  3388.     archived (see question 17.33).  The comp.archives newsgroup
  3389.     contains numerous announcements of anonymous ftp availability of
  3390.     various items.  The "archie" mailserver can tell you which
  3391.     anonymous ftp sites have which packages; send the mail message
  3392.     "help" to archie@quiche.cs.mcgill.ca for information.  Finally,
  3393.     the newsgroup comp.sources.wanted is generally a more
  3394.     appropriate place to post queries for source availability, but
  3395.     check _its_ FAQ list, "How to find sources," before posting
  3396.     there.
  3397.  
  3398. 17.13:    When will the next International Obfuscated C Code Contest
  3399.     (IOCCC) be held?  How can I get a copy of the current and
  3400.     previous winning entries?
  3401.  
  3402. A:    The contest typically runs from early March through mid-May.  To
  3403.     obtain a current copy of the rules and guidelines, send e-mail
  3404.     with the Subject: line "send rules" to:
  3405.  
  3406.         {apple,pyramid,sun,uunet}!hoptoad!judges  or
  3407.         judges@toad.com
  3408.  
  3409.     (Note that these are _not_ the addresses for submitting
  3410.     entries.)
  3411.  
  3412.     Contest winners are first announced at the Summer Usenix
  3413.     Conference in mid-June, and posted to the net sometime in July-
  3414.     August.  Winning entries from previous years (to 1984) are
  3415.     archived at uunet (see question 17.12) under the directory
  3416.     ~/pub/ioccc.
  3417.  
  3418.     As a last resort, previous winners may be obtained by sending
  3419.     e-mail to the above address, using the Subject: "send YEAR
  3420.     winners", where YEAR is a single four-digit year, a year range,
  3421.     or "all".
  3422.  
  3423. 17.14:    Why don't C comments nest?  How am I supposed to comment out
  3424.     code containing comments?  Are comments legal inside quoted
  3425.     strings?
  3426.  
  3427. A:    Nested comments would cause more harm than good, mostly because
  3428.     of the possibility of accidentally leaving comments unclosed by
  3429.     including the characters "/*" within them.  For this reason, it
  3430.     is usually better to "comment out" large sections of code, which
  3431.     might contain comments, with #ifdef or #if 0 (but see question
  3432.     5.11).
  3433.  
  3434.     The character sequences /* and */ are not special within
  3435.     double-quoted strings, and do not therefore introduce comments,
  3436.     because a program (particularly one which is generating C code
  3437.     as output) might want to print them.
  3438.  
  3439.     References: ANSI Appendix E p. 198, Rationale Sec. 3.1.9 p. 33.
  3440.  
  3441. 17.15:    How can I get the ASCII value corresponding to a character, or
  3442.     vice versa?
  3443.  
  3444. A:    In C, characters are represented by small integers corresponding
  3445.     to their values (in the machine's character set) so you don't
  3446.     need a conversion routine: if you have the character, you have
  3447.     its value.
  3448.  
  3449. 17.16:    How can I implement sets and/or arrays of bits?
  3450.  
  3451. A:    Use arrays of char or int, with a few macros to access the right
  3452.     bit at the right index (try using 8 for CHAR_BIT if you don't
  3453.     have <limits.h>):
  3454.  
  3455.         #include <limits.h>        /* for CHAR_BIT */
  3456.  
  3457.         #define BITMASK(bit) (1 << ((bit) % CHAR_BIT))
  3458.         #define BITSLOT(bit) ((bit) / CHAR_BIT)
  3459.         #define BITSET(ary, bit) ((ary)[BITSLOT(bit)] |= BITMASK(bit))
  3460.         #define BITTEST(ary, bit) ((ary)[BITSLOT(bit)] & BITMASK(bit))
  3461.  
  3462. 17.17:    What is the most efficient way to count the number of bits which
  3463.     are set in a value?
  3464.  
  3465. A:    This and many other similar bit-twiddling problems can often be
  3466.     sped up and streamlined using lookup tables (but see the next
  3467.     question).
  3468.  
  3469. 17.18:    How can I make this code more efficient?
  3470.  
  3471. A:    Efficiency, though a favorite comp.lang.c topic, is not
  3472.     important nearly as often as people tend to think it is.  Most
  3473.     of the code in most programs is not time-critical.  When code is
  3474.     not time-critical, it is far more important that it be written
  3475.     clearly and portably than that it be written maximally
  3476.     efficiently.  (Remember that computers are very, very fast, and
  3477.     that even "inefficient" code can run without apparent delay.)
  3478.  
  3479.     It is notoriously difficult to predict what the "hot spots" in a
  3480.     program will be.  When efficiency is a concern, it is important
  3481.     to use profiling software to determine which parts of the
  3482.     program deserve attention.  Often, actual computation time is
  3483.     swamped by peripheral tasks such as I/O and memory allocation,
  3484.     which can be sped up by using buffering and caching techniques.
  3485.  
  3486.     For the small fraction of code that is time-critical, it is
  3487.     vital to pick a good algorithm; it is less important to
  3488.     "microoptimize" the coding details.  Many of the "efficient
  3489.     coding tricks" which are frequently suggested (e.g. substituting
  3490.     shift operators for multiplication by powers of two) are
  3491.     performed automatically by even simpleminded compilers.
  3492.     Heavyhanded "optimization" attempts can make code so bulky that
  3493.     performance is degraded.
  3494.  
  3495.     For more discussion of efficiency tradeoffs, as well as good
  3496.     advice on how to increase efficiency when it is important, see
  3497.     chapter 7 of Kernighan and Plauger's The Elements of Programming
  3498.     Style, and Jon Bentley's Writing Efficient Programs.
  3499.  
  3500. 17.19:    Are pointers really faster than arrays?  How much do function
  3501.     calls slow things down?  Is ++i faster than i = i + 1?
  3502.  
  3503. A:    Precise answers to these and many similar questions depend of
  3504.     course on the processor and compiler in use.  If you simply must
  3505.     know, you'll have to time test programs carefully.  (Often the
  3506.     differences are so slight that hundreds of thousands of
  3507.     iterations are required even to see them.  Check the compiler's
  3508.     assembly language output, if available, to see if two purported
  3509.     alternatives aren't compiled identically.)
  3510.  
  3511.     It is "usually" faster to march through large arrays with
  3512.     pointers rather than array subscripts, but for some processors
  3513.     the reverse is true.
  3514.  
  3515.     Function calls, though obviously incrementally slower than in-
  3516.     line code, contribute so much to modularity and code clarity
  3517.     that there is rarely good reason to avoid them.
  3518.  
  3519.     Before rearranging expressions such as i = i + 1, remember that
  3520.     you are dealing with a C compiler, not a keystroke-programmable
  3521.     calculator.  Any decent compiler will generate identical code
  3522.     for ++i, i += 1, and i = i + 1.  The reasons for using ++i or
  3523.     i += 1 over i = i + 1 have to do with style, not efficiency.
  3524.     (See also question 4.7.)
  3525.  
  3526. 17.20:    Why does this code:
  3527.  
  3528.         char *p = "Hello, world!";
  3529.         p[0] = tolower(p[0]);
  3530.  
  3531.     crash?
  3532.  
  3533. A:    String literals are not necessarily modifiable, except (in
  3534.     effect) when they are used as array initializers.  Try
  3535.  
  3536.         char a[] = "Hello, world!";
  3537.  
  3538.     (For compiling old code, some compilers have a switch
  3539.     controlling whether strings are writable or not.)  See also
  3540.     questions 2.1, 2.2, 2.8, and 17.2.
  3541.  
  3542.     References: ANSI Sec. 3.1.4 .
  3543.  
  3544. 17.21:    This program crashes before it even runs!  (When single-stepping
  3545.     with a debugger, it dies before the first statement in main.)
  3546.  
  3547. A:    You probably have one or more very large (kilobyte or more)
  3548.     local arrays.  Many systems have fixed-size stacks, and those
  3549.     which perform dynamic stack allocation automatically (e.g. Unix)
  3550.     can be confused when the stack tries to grow by a huge chunk all
  3551.     at once.
  3552.  
  3553.     It is often better to declare large arrays with static duration
  3554.     (unless of course you need a fresh set with each recursive
  3555.     call).
  3556.  
  3557.     (See also question 9.4.)
  3558.  
  3559. 17.22:    What do "Segmentation violation" and "Bus error" mean?
  3560.  
  3561. A:    These generally mean that your program tried to access memory it
  3562.     shouldn't have, invariably as a result of improper pointer use,
  3563.     often involving uninitialized or improperly allocated pointers
  3564.     (see questions 3.1 and 3.2), or malloc (see question 17.23), or
  3565.     perhaps scanf (see question 11.2).
  3566.  
  3567. 17.23:    My program is crashing, apparently somewhere down inside malloc,
  3568.     but I can't see anything wrong with it.
  3569.  
  3570. A:    It is unfortunately very easy to corrupt malloc's internal data
  3571.     structures, and the resulting problems can be hard to track
  3572.     down.  The most common source of problems is writing more to a
  3573.     malloc'ed region than it was allocated to hold; a particularly
  3574.     common bug is to malloc(strlen(s)) instead of strlen(s) + 1.
  3575.     Other problems involve freeing pointers not obtained from
  3576.     malloc, or trying to realloc a null pointer (see question 3.12).
  3577.  
  3578.     A number of debugging packages exist to help track down malloc
  3579.     problems; one popular one is Conor P. Cahill's "dbmalloc,"
  3580.     posted to comp.sources.misc in September of 1992.  Others are
  3581.     "leak," available in volume 27 of the comp.sources.unix
  3582.     archives; JMalloc.c and JMalloc.h in Fidonet's C_ECHO Snippets
  3583.     (or ask archie; see question 17.12); and MEMDEBUG from
  3584.     dorado.crpht.lu in pub/sources/memdebug .  See also question
  3585.     17.12.
  3586.  
  3587. 17.24:    Does anyone have a C compiler test suite I can use?
  3588.  
  3589. A:    Plum Hall (formerly in Cardiff, NJ; now in Hawaii) sells one.
  3590.     The FSF's GNU C (gcc) distribution includes a c-torture-
  3591.     test.tar.Z which checks a number of common problems with
  3592.     compilers.  Kahan's paranoia test, found in netlib/paranoia on
  3593.     netlib.att.com, strenuously tests a C implementation's floating
  3594.     point capabilities.
  3595.  
  3596. 17.25:    Where can I get a YACC grammar for C?
  3597.  
  3598. A:    The definitive grammar is of course the one in the ANSI
  3599.     standard.  Another grammar, by Jim Roskind, is in pub/*grammar*
  3600.     at ics.uci.edu .  A fleshed-out, working instance of the ANSI
  3601.     grammar (due to Jeff Lee) is on uunet (see question 17.12) in
  3602.     usenet/net.sources/ansi.c.grammar.Z (including a companion
  3603.     lexer).  The FSF's GNU C compiler contains a grammar, as does
  3604.     the appendix to K&R II.
  3605.  
  3606.     References: ANSI Sec. A.2 .
  3607.  
  3608. 17.26:    I need code to parse and evaluate expressions.
  3609.  
  3610. A:    Two available packages are "defunc," posted to comp.source.misc
  3611.     in December, 1993 (V41 i32,33), to alt.sources in January, 1994,
  3612.     and available from sunsite.unc.edu in
  3613.     pub/packages/development/libraries/defunc-1.3.tar.Z; and
  3614.     "parse," at lamont.ldgo.columbia.edu.
  3615.  
  3616. 17.27:    I need a sort of an "approximate" strcmp routine, for comparing
  3617.     two strings for close, but not necessarily exact, equality.
  3618.  
  3619. A:    The traditional routine for doing this sort of thing involves
  3620.     the "soundex" algorithm, which maps similar-sounding words to
  3621.     the same numeric codes.  Soundex is described in the Searching
  3622.     and Sorting volume of Donald Knuth's classic _The Art of
  3623.     Computer Programming_.
  3624.  
  3625. 17.28:    How can I find the day of the week given the date?
  3626.  
  3627. A:    Use mktime (see questions 12.6 and 12.7), or Zeller's
  3628.     congruence.  Here is one quick implementation posted by Tomohiko
  3629.     Sakamoto:
  3630.  
  3631.         dayofweek(y, m, d)    /* 0 = Sunday */
  3632.         int y, m, d;        /* 1 <= m <= 12,  y > 1752 or so */
  3633.         {
  3634.             static int t[] = {0, 3, 2, 5, 0, 3, 5, 1, 4, 6, 2, 4};
  3635.             y -= m < 3;
  3636.             return (y + y/4 - y/100 + y/400 + t[m-1] + d) % 7;
  3637.         }
  3638.  
  3639. 17.29:    Will 2000 be a leap year?  Is (year % 4 == 0) an accurate test
  3640.     for leap years?
  3641.  
  3642. A:    Yes and no, respectively.  The full expression for the Gregorian
  3643.     calendar is
  3644.  
  3645.         year % 4 == 0 && (year % 100 != 0 || year % 400 == 0)
  3646.  
  3647.     See a good astronomical almanac or other reference for details.
  3648.  
  3649. 17.30:    How do you pronounce "char"?
  3650.  
  3651. A:    You can pronounce the C keyword "char" in at least three ways:
  3652.     like the English words "char," "care," or "car;" the choice is
  3653.     arbitrary.
  3654.  
  3655. 17.31:    What's a good book for learning C?
  3656.  
  3657. A:    Mitch Wright maintains an annotated bibliography of C and Unix
  3658.     books; it is available for anonymous ftp from ftp.rahul.net in
  3659.     directory pub/mitch/YABL.
  3660.  
  3661.     This FAQ list's editor maintains a collection of previous
  3662.     answers to this question, which is available upon request.
  3663.  
  3664. 17.32:    Are there any C tutorials on the net?
  3665.  
  3666. A:    There are at least two of them:
  3667.  
  3668.     "Notes for C programmers," by Christopher Sawtell,
  3669.     available from:
  3670.     svr-ftp.eng.cam.ac.uk:misc/sawtell_C.shar
  3671.     garbo.uwasa.fi:/pc/c/c-lesson.zip
  3672.     oak.oakland.edu:pub/msdos/c/LEARN-C.ZIP
  3673.     paris7.jussieu.fr:/contributions/docs
  3674.  
  3675.     Tim Love's "C for Programmers,"
  3676.     available from svr-ftp.eng.cam.ac.uk in the misc directory.
  3677.  
  3678. 17.33:    Where can I get extra copies of this list?  What about back
  3679.     issues?
  3680.  
  3681. A:    For now, just pull it off the net; it is normally posted to
  3682.     comp.lang.c on the first of each month, with an Expires: line
  3683.     which should keep it around all month.  An abridged version is
  3684.     also available (and posted), as is a list of changes
  3685.     accompanying each significantly updated version.  These lists
  3686.     can also be found in the newsgroups comp.answers and
  3687.     news.answers .  Several sites archive news.answers postings and
  3688.     other FAQ lists, including this one: two sites are rtfm.mit.edu
  3689.     (directories pub/usenet/news.answers/C-faq/ and
  3690.     pub/usenet/comp.lang.c/ ) and ftp.uu.net (directory
  3691.     usenet/news.answers/C-faq/ ).  The archie server should help you
  3692.     find others; query it for "prog C-faq".  See the meta-FAQ list
  3693.     in news.answers for more information; see also question 17.12.
  3694.  
  3695.     This list is an evolving document of questions which have been
  3696.     Frequent since before the Great Renaming, not just a collection
  3697.     of this month's interesting questions.  Older copies are
  3698.     obsolete and don't contain much, except the occasional typo,
  3699.     that the current list doesn't.
  3700.  
  3701.  
  3702. Bibliography
  3703.  
  3704. ANSI    American National Standard for Information Systems --
  3705.     Programming Language -- C, ANSI X3.159-1989 (see question 5.2).
  3706.  
  3707. JLB    Jon Louis Bentley, Writing Efficient Programs, Prentice-Hall,
  3708.     1982, ISBN 0-13-970244-X.
  3709.  
  3710. H&S    Samuel P. Harbison and Guy L. Steele, C: A Reference Manual,
  3711.     Second Edition, Prentice-Hall, 1987, ISBN 0-13-109802-0.  (A
  3712.     third edition has recently been released.)
  3713.  
  3714. PCS    Mark R. Horton, Portable C Software, Prentice Hall, 1990,
  3715.     ISBN 0-13-868050-7.
  3716.  
  3717. EoPS    Brian W. Kernighan and P.J. Plauger, The Elements of Programming
  3718.     Style, Second Edition, McGraw-Hill, 1978, ISBN 0-07-034207-5.
  3719.  
  3720. K&R I    Brian W. Kernighan and Dennis M. Ritchie, The C Programming
  3721.     Language, Prentice-Hall, 1978, ISBN 0-13-110163-3.
  3722.  
  3723. K&R II    Brian W. Kernighan and Dennis M. Ritchie, The C Programming
  3724.     Language, Second Edition, Prentice Hall, 1988, ISBN 0-13-
  3725.     110362-8, 0-13-110370-9.
  3726.  
  3727. Knuth    Donald E. Knuth, The Art of Computer Programming, (3 vols.),
  3728.     Addison-Wesley, 1981.
  3729.  
  3730. CT&P    Andrew Koenig, C Traps and Pitfalls, Addison-Wesley, 1989,
  3731.     ISBN 0-201-17928-8.
  3732.  
  3733.     P.J. Plauger, The Standard C Library, Prentice Hall, 1992,
  3734.     ISBN 0-13-131509-9.
  3735.  
  3736.     Harry Rabinowitz and Chaim Schaap, Portable C, Prentice-Hall,
  3737.     1990, ISBN 0-13-685967-4.
  3738.  
  3739. There is a more extensive bibliography in the revised Indian Hill style
  3740. guide (see question 14.3).  See also question 17.31.
  3741.  
  3742.  
  3743. Acknowledgements
  3744.  
  3745. Thanks to Jamshid Afshar, Sudheer Apte, Randall Atkinson, Dan Bernstein,
  3746. Vincent Broman, Stan Brown, Joe Buehler, Gordon Burditt, Burkhard Burow,
  3747. Conor P. Cahill, D'Arcy J.M. Cain, Christopher Calabrese, Ian Cargill,
  3748. Paul Carter, Raymond Chen, Jonathan Coxhead, Lee Crawford, Steve Dahmer,
  3749. Andrew Daviel, James Davies, Jutta Degener, Norm Diamond, Jeff Dunlop,
  3750. Ray Dunn, Stephen M. Dunn, Michael J. Eager, Dave Eisen, Bjorn Engsig,
  3751. Chris Flatters, Rod Flores, Alexander Forst, Jeff Francis, Dave
  3752. Gillespie, Samuel Goldstein, Alasdair Grant, Ron Guilmette, Doug Gwyn,
  3753. Tony Hansen, Joe Harrington, Guy Harris, Elliotte Rusty Harold, Jos
  3754. Horsmeier, Blair Houghton, Ke Jin, Kirk Johnson, Larry Jones, Kin-ichi
  3755. Kitano, Peter Klausler, Andrew Koenig, Tom Koenig, Ajoy Krishnan T,
  3756. Markus Kuhn, John Lauro, Felix Lee, Mike Lee, Timothy J. Lee, Tony Lee,
  3757. Don Libes, Christopher Lott, Tim Love, Tim McDaniel, Stuart MacMartin,
  3758. John R. MacMillan, Bob Makowski, Evan Manning, Barry Margolin, George
  3759. Matas, Brad Mears, Bill Mitchell, Mark Moraes, Darren Morby, Ken Nakata,
  3760. Landon Curt Noll, David O'Brien, Richard A. O'Keefe, Hans Olsson, Philip
  3761. (lijnzaad@embl-heidelberg.de), Christopher Phillips, Francois Pinard,
  3762. Dan Pop, Kevin D. Quitt, Pat Rankin, J. M. Rosenstock, Erkki Ruohtula,
  3763. Tomohiko Sakamoto, Rich Salz, Chip Salzenberg, Paul Sand, DaviD
  3764. W. Sanderson, Christopher Sawtell, Paul Schlyter, Doug Schmidt, Rene
  3765. Schmit, Patricia Shanahan, Peter da Silva, Joshua Simons, Henry Spencer,
  3766. David Spuler, Melanie Summit, Erik Talvola, Clarke Thatcher, Wayne
  3767. Throop, Chris Torek, Andrew Tucker, Goran Uddeborg, Rodrigo Vanegas, Jim
  3768. Van Zandt, Wietse Venema, Ed Vielmetti, Larry Virden, Chris Volpe, Mark
  3769. Warren, Larry Weiss, Freek Wiedijk, Lars Wirzenius, Dave Wolverton,
  3770. Mitch Wright, Conway Yee, and Zhuo Zang, who have contributed, directly
  3771. or indirectly, to this article.  Special thanks to Karl Heuer, and
  3772. particularly to Mark Brader, who (to borrow a line from Steve Johnson)
  3773. have goaded me beyond my inclination, and occasionally beyond my
  3774. endurance, in relentless pursuit of a better FAQ list.
  3775.  
  3776.                     Steve Summit
  3777.                     scs@eskimo.com
  3778.  
  3779. This article is Copyright 1988, 1990-1994 by Steve Summit.
  3780. It may be freely redistributed so long as the author's name, and this
  3781. notice, are retained.
  3782. The C code in this article (vstrcat(), error(), etc.) is public domain
  3783. and may be used without restriction.
  3784.